package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.enums.ProductStatusEnums;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.constants.ProductForumConstant;
import com.ytjj.qmyx.admin.constants.SysConfigConstants;
import com.ytjj.common.constants.PlatformConstant;
import com.ytjj.qmyx.admin.dao.*;
import com.ytjj.qmyx.admin.dao.channel.ChannelLabelDao;
import com.ytjj.qmyx.admin.dao.channel.SalesChannelsManagementDao;
import com.ytjj.qmyx.admin.eunm.ActivityEnums;
import com.ytjj.qmyx.admin.eunm.ActivityTypeNameCode;
import com.ytjj.qmyx.admin.eunm.ForumEnum;
import com.ytjj.qmyx.admin.eunm.ForumEnumNew;
import com.ytjj.qmyx.admin.mapper.*;
import com.ytjj.qmyx.admin.model.*;
import com.ytjj.qmyx.admin.model.SalesChannelsManagement;
import com.ytjj.qmyx.admin.model.request.*;
import com.ytjj.qmyx.admin.model.response.*;
import com.ytjj.qmyx.admin.model.response.goods.ProductImgResponse;
import com.ytjj.qmyx.admin.service.*;
import com.ytjj.qmyx.admin.service.channelProductService.ChannelProductService;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.BankerRequest;
import com.ytjj.qmyx.mall.model.BankerResponse;
import com.ytjj.qmyx.mall.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.LinkedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductDao productDao;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductAttributeKeyMapper productAttributeKeyMapper;

    @Resource
    private ProductAttributeValueMapper productAttributeValueMapper;

    @Resource
    private ProductSpecMapper productSpecMapper;

    @Resource
    private ProductActivitySpecMapper productActivitySpecMapper;

    @Resource
    private ProductActivityMapper productActivityMapper;

    @Resource
    private ActivityColumnMapper activityColumnMapper;

    @Resource
    private ProductCategoryMapper productCategoryMapper;

    @Resource
    private BankerMapper bankerMapper;

    @Resource
    private ProductImgMapper productImgMapper;

    @Resource
    private ProductForumInfoMapper productForumInfoMapper;

    @Resource
    private ProductActivityImgMapper productActivityImgMapper;

    @Resource
    private ProductSkuValueMapper productSkuValueMapper;

    @Resource
    private ProductSkuKeyMapper productSkuKeyMapper;

    @Resource
    private ProductActivitySkuKeyMapper productActivitySkuKeyMapper;

    @Resource
    private ProductActivitySkuValueMapper productActivitySkuValueMapper;

    @Resource
    private ProductMatchingMapper productMatchingMapper;

    @Resource
    private ProductActivityMatchingMapper productActivityMatchingMapper;

    @Resource
    private ProductMatchingDao productMatchingDao;

    @Resource
    private ProductSpecDao productSpecDao;

    @Resource
    private ProductSpecialMapper productSpecialMapper;

    @Resource
    private ProductStatisticsDao productStatisticsDao;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private ProductSpecialDao productSpecialDao;

    @Resource
    private ProductActivityDao productActivityDao;

    @Resource
    private ProductImgDao productImgDao;

    @Resource
    private EvaluationProductImgMapper evaluationProductImgMapper;

    @Resource
    private EvaluationProductSpecMapper evaluationProductSpecMapper;

    @Resource
    private EvaluationProductSkuKeyMapper evaluationProductSkuKeyMapper;

    @Resource
    private EvaluationProductSkuValueMapper evaluationProductSkuValueMapper;

    @Autowired
    private BankerMessageDao bankerMessageDao;

    @Resource
    private BankerColumnMapper bankerColumnMapper;

    @Resource
    private BankerDao bankerDao;

    @Resource
    private BankerProductDao bankerProductDao;

    @Resource
    private ProductCategoryDao productCategoryDao;

    @Resource
    private ProductForumDao productForumDao;

    @Resource
    private ProductForumMapper productForumMapper;
    @Autowired
    private BankerBrandService bankerBrandService;

    @Resource
    private CategoryNowMapper categoryNowMapper;

    @Autowired
    private CategoryNowService categoryNowService;

    @Resource
    private ProductLabelDao productLabelDao;
    @Resource
    private ChannelLabelDao channelLabelDao;

    @Autowired
    private SupplyApiConfig supplyApiConfig;

    @Autowired
    private ChannelProductService channelProductService;

    @Resource
    private SpecialMapper specialMapper;

    @Resource
    private ProductBrandMapper productBrandMapper;

    @Resource
    private ProductSubjectPlateDao productSubjectPlateDao;
    @Resource
    private ProductReviewsMapper productReviewsMapper;
    @Resource
    private SalesChannelsManagementDao salesChannelsManagementDao;

    /**
     * 商品导出是否多规格方式
     * 1-是  0-不是
     */
    @Value("${qmyx.product.download.more_spec:1}")
    private Integer moreSpec;


    @Override
    public CommonPage<ProductModelResponse> selectList(ProductRequest productRequest) {
        if(!StringUtils.isEmpty(productRequest.getBankerName()) && !productRequest.getBankerName().equals("")) {
            Map map = new HashMap();
            map.put("bankerName", productRequest.getBankerName());
            String bankerIds = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/getBankerIdByBankerName", map, supplyApiConfig.getHeadsMap());
            List<Integer> integers = JSONObject.parseArray(bankerIds, Integer.class);
            productRequest.setBankerIds(integers);
        }
        PageHelper.startPage(productRequest.getPageNum(), productRequest.getPageSize());
        List<ProductModelResponse> page = productDao.selectList(productRequest);

        if (!CollectionUtils.isEmpty(page)) {
            //供应商id
            List<Integer> bankerIds = page.stream().filter(item ->null != item.getBankerId()).map(ProductModelResponse::getBankerId).collect(Collectors.toList());
            //查询供应商名称
            BankerRequest bankerRequest = new BankerRequest();
            bankerRequest.setBankerIdList(bankerIds);
            String jsonRequest = JSON.toJSONString(bankerRequest);
            String resultString = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getBankerMsg", jsonRequest, supplyApiConfig.getHeadsMap());
            List<BankerResponse> bankerResponses = JSONObject.parseArray(resultString, BankerResponse.class);

            //供应链商品id
            List<Integer> supplyProductIds = page.stream().filter(item ->null != item.getSupplyProductId()).map(ProductModelResponse::getSupplyProductId).collect(Collectors.toList());
            //查询供应链商品信息
            List<YxProduct> yxProducts = new ArrayList<>();
            if (!CollectionUtils.isEmpty(supplyProductIds)){
                ProductReceiveRequest productReceiveRequest = new ProductReceiveRequest();
                productReceiveRequest.setProductIds(supplyProductIds);
                String json = JSON.toJSONString(productReceiveRequest);
                String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getByIds", json, supplyApiConfig.getHeadsMap());
                yxProducts = JSONObject.parseArray(result, YxProduct.class);
            }

            List<Integer> collect = page.stream().map(ProductModelResponse::getId).collect(Collectors.toList());
            List<ProductLabel> productLabelsList = productLabelDao.selectByProductIds(collect);

            //获取销售渠道所有商品
            List<ProductCategory> productCategoryAllList = channelProductService.getAllProductCategorys();
            List<ProductImg> productImgList = productImgDao.getProductImgByTypeByProductId(Arrays.asList("banner", "info"), collect);
            for (ProductModelResponse productModelResponse : page) {

                List<BankerResponse> bankerResponse = bankerResponses.stream().filter(item -> item.getBankerId().equals(productModelResponse.getBankerId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(bankerResponse)){
                    //供应商名称//供应商名称从warehouseName获取
                    productModelResponse.setBankerName(bankerResponse.get(0).getBankerName());
                }

                //商品供货价/总库存
                List<YxProduct> collect1 = yxProducts.stream().filter(yxProduct -> yxProduct.getId().equals(productModelResponse.getSupplyProductId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect1)){
                    productModelResponse.setSupplyPrice(collect1.get(0).getSupplyPrice());
                    productModelResponse.setStock(collect1.get(0).getStock());
                }

                //商品标签
                List<ProductLabel> productLabels = productLabelsList.stream().filter(item -> item.getProductId().equals(productModelResponse.getId())).collect(Collectors.toList());
                StringBuffer productLabelStr = new StringBuffer();
                List<Integer> productLabelIds = new ArrayList<>();
                if (!CollectionUtils.isEmpty(productLabels)){
                    productLabels.forEach(productLabel -> {
                        productLabelIds.add(productLabel.getProductLabelId());
                        productLabelStr.append(productLabel.getProductLabelName()).append(" ");
                    });
                    productModelResponse.setProductLabelList(productLabels);
                    productModelResponse.setProductLabelIds(productLabelIds);
                }
                //渠道标签
                List<ChannelLabel> channelLabelList = channelLabelDao.findByProductId(productModelResponse.getPlatformData(),productModelResponse.getId());
                productModelResponse.setChannelProductLabelList(channelLabelList);

                //dataSource 转换成数组返回
                String dataSource = productModelResponse.getDataSource();
                if (!StringUtils.isEmpty(dataSource)) {
                    List<String> dataSourceList = new ArrayList<>();
                    String[] split = dataSource.split(",");
                    for (String s : split) {
                        dataSourceList.add(s);
                    }
                    productModelResponse.setDataSourceList(dataSourceList);
                }

                // 产品分类
                productCategoryAllList.stream().forEach(s -> {
                    if (null != productModelResponse.getTopCategoryId() && productModelResponse.getTopCategoryId().equals(s.getId())) {
                        productModelResponse.setCategoryTopTitle(s.getTitle());
                    }
                    if (null != productModelResponse.getCategoryId() && productModelResponse.getCategoryId().equals(s.getId())) {
                        productModelResponse.setCategoryTitle(s.getTitle());
                    }
                    if (null != productModelResponse.getBottomCategoryId() && productModelResponse.getBottomCategoryId().equals(s.getId())) {
                        productModelResponse.setCategoryBottomTitle(s.getTitle());
                    }
                });

//                List<ProductImg> imgInfoList = productImgDao.getProductImgByIdAndType(productModelResponse.getId(), Arrays.asList("banner", "info"));
                if (!CollectionUtils.isEmpty(productImgList)) {
                    List<ProductImg> imgInfoList = productImgList.stream().filter(item ->
                            item.getProductId().equals(productModelResponse.getId())).collect(Collectors.toList());
                    List<ProductImg> bannerList = new ArrayList<>();
                    List<ProductImg> infoList = new ArrayList<>();
                    imgInfoList.stream().forEach(s -> {
                        if ("banner".equals(s.getType())) {
                            bannerList.add(s);
                        }
                        if ("info".equals(s.getType())) {
                            infoList.add(s);
                        }
                    });
                    productModelResponse.setBannerImgList(bannerList);
                    productModelResponse.setDetailList(infoList);
                }


                // 毛利率
                BigDecimal price = null == productModelResponse.getPrice() ? BigDecimal.ZERO : productModelResponse.getPrice();
                BigDecimal costPrice = productModelResponse.getCostPrice();
                BigDecimal grossProfit = new BigDecimal(0);
                String grossProfixRate = "0.00";
                if (price.compareTo(BigDecimal.ZERO) != 0 && price != null) {
                    grossProfit = price.subtract(costPrice).divide(price, 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                    DecimalFormat df = new DecimalFormat("0.00");
                    grossProfixRate = df.format(grossProfit);
                }
                productModelResponse.setGrossProfitRate(grossProfixRate);

                // 补贴力度
                BigDecimal productPrice = Optional.ofNullable(productModelResponse.getPrice()).orElse(BigDecimal.ZERO);
                BigDecimal subsidy = null == productModelResponse.getOriginalPrice() ? BigDecimal.ZERO :
                        productModelResponse.getOriginalPrice().subtract(productPrice);
                productModelResponse.setSubsidy(subsidy.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : subsidy);
                //解析活动栏目
                String activityColumnName="";
                String activityColumnIds=productModelResponse.getActivityColumnIds();
                List<Integer> activityColumnIdList = new ArrayList<>();
                if(org.apache.commons.lang3.StringUtils.isNotBlank(activityColumnIds)){
                    try {
                        String[] activityColumnIdArray = activityColumnIds.split(",");

                        ActivityColumnExample example = new ActivityColumnExample();
                        activityColumnIdList = Arrays.asList(activityColumnIdArray).stream().map(Integer::parseInt).collect(Collectors.toList());
                        example.createCriteria().andIdIn(activityColumnIdList);
                        List<ActivityColumn> activityColumns = activityColumnMapper.selectByExample(example);

                        if (!CollectionUtils.isEmpty(activityColumns)) {
                            activityColumnName = String.join(",", activityColumns.stream().map(ActivityColumn::getTitle).collect(Collectors.toList()));
                        }

                    }catch (Exception e){
                        log.error("解析活动栏目id错误",e);
                    }
                    productModelResponse.setActivityColumnName(activityColumnName);
                }else{
                    productModelResponse.setActivityColumnName("");
                }
                productModelResponse.setActivityColumnIdList(activityColumnIdList);

                // 商品类型
                productModelResponse.setActivityTypeName(ActivityTypeNameCode.getName(productModelResponse.getActivityType()));

                // 活动类型列表
                ProductActivityExample productActivityExample = new ProductActivityExample();
                productActivityExample.createCriteria().andProductIdEqualTo(productModelResponse.getId());
                List<ProductActivity> productActivitys = productActivityMapper.selectByExample(productActivityExample);

                productModelResponse.setProductActivity(productActivitys);

                // 测评类型
                if (productModelResponse.getIsZeroProduct() == 1 && productModelResponse.getStockEvaluation() == 0) {
                    productModelResponse.setEvaluationType(2);
                } else if (productModelResponse.getIsZeroProduct() == 1 && productModelResponse.getStockEvaluation() > 0) {
                    productModelResponse.setEvaluationType(1);
                } else {
                    productModelResponse.setEvaluationType(3);
                }
                if (!StringUtils.isEmpty(productRequest.getActivityType()) && null == productRequest.getEnterType()) {
                    productModelResponse.setCreateTime(productModelResponse.getActivityTime());
                }
            }
        }
        return CommonPage.restPage(page);
    }

    /**
     * 按新的分类搜索
     * @param productRequest:
     * @returns: com.ytjj.common.api.CommonPage<com.ytjj.qmyx.admin.model.response.ProductModelResponse>
     * 
     */
    @Override
    public CommonPage<ProductModelResponse> selectListV2(ProductRequest productRequest) {
        PageHelper.startPage(productRequest.getPageNum(), productRequest.getPageSize());

        List<ProductModelResponse> page = productDao.selectListV2(productRequest);
        if (!CollectionUtils.isEmpty(page)) {
            List<CategoryNow> productCategoryAllList = categoryNowMapper.selectByExample(new CategoryNowExample());
            for (ProductModelResponse productModelResponse : page) {
                //dataSource 转换成数组返回
                String dataSource = productModelResponse.getDataSource();
                if (!StringUtils.isEmpty(dataSource)) {
                    List<String> dataSourceList = new ArrayList<>();
                    String[] split = dataSource.split(",");
                    for (String s : split) {
                        dataSourceList.add(s);
                    }
                    productModelResponse.setDataSourceList(dataSourceList);
                }

                // 产品分类
                productCategoryAllList.stream().forEach(s -> {
                    if (null != productModelResponse.getTopCategoryId() && productModelResponse.getTopCategoryId().equals(s.getId())) {
                        productModelResponse.setCategoryTopTitle(s.getTitle());
                    }
                    if (null != productModelResponse.getCategoryId() && productModelResponse.getCategoryId().equals(s.getId())) {
                        productModelResponse.setCategoryTitle(s.getTitle());
                    }
                    if (null != productModelResponse.getBottomCategoryId() && productModelResponse.getBottomCategoryId().equals(s.getId())) {
                        productModelResponse.setCategoryBottomTitle(s.getTitle());
                    }
                });

                List<ProductImg> imgInfoList = productImgDao.getProductImgByIdAndType(productModelResponse.getId(), Arrays.asList("banner", "info"));
                List<ProductImg> bannerList = new ArrayList<>();
                List<ProductImg> infoList = new ArrayList<>();
                imgInfoList.stream().forEach(s -> {
                    if ("banner".equals(s.getType())) {
                        bannerList.add(s);
                    }
                    if ("info".equals(s.getType())) {
                        infoList.add(s);
                    }
                });
                productModelResponse.setBannerImgList(bannerList);
                productModelResponse.setDetailList(infoList);

                // 毛利率
                BigDecimal price = null == productModelResponse.getPrice() ? BigDecimal.ZERO : productModelResponse.getPrice();
                BigDecimal costPrice = productModelResponse.getCostPrice();
                BigDecimal grossProfit = new BigDecimal(0);
                String grossProfixRate = "0.00";
                if (price.compareTo(BigDecimal.ZERO) != 0 && price != null) {
                    grossProfit = price.subtract(costPrice).divide(price, 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                    DecimalFormat df = new DecimalFormat("0.00");
                    grossProfixRate = df.format(grossProfit);
                }
                productModelResponse.setGrossProfitRate(grossProfixRate);

                // 补贴力度
                BigDecimal subsidy = null == productModelResponse.getOriginalPrice() ? BigDecimal.ZERO : productModelResponse.getOriginalPrice().subtract(productModelResponse.getPrice());
                productModelResponse.setSubsidy(subsidy.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : subsidy);
                //解析活动栏目
                String activityColumnName="";
                String activityColumnIds=productModelResponse.getActivityColumnIds();
                List<Integer> activityColumnIdList = new ArrayList<>();
                if(org.apache.commons.lang3.StringUtils.isNotBlank(activityColumnIds)){
                    try {
                        String[] activityColumnIdArray = activityColumnIds.split(",");
                        if (activityColumnIdArray != null && activityColumnIdArray.length > 0) {
                            for(int i=0;i<activityColumnIdArray.length;i++) {
                                int columnId=Integer.parseInt(activityColumnIdArray[i]);
                                activityColumnIdList.add(columnId);
                                ActivityColumn activityColumn = activityColumnMapper.selectByPrimaryKey(columnId);
                                if (activityColumn != null) {
                                    if(org.apache.commons.lang3.StringUtils.isBlank(activityColumnName)) {
                                        activityColumnName = activityColumn.getTitle();
                                    }else{
                                        activityColumnName += ","+activityColumn.getTitle();
                                    }
                                }
                            }
                        }
                    }catch (Exception e){
                        log.error("解析活动栏目id错误",e);
                    }
                    productModelResponse.setActivityColumnName(activityColumnName);
                }else{
                    productModelResponse.setActivityColumnName("");
                }
                productModelResponse.setActivityColumnIdList(activityColumnIdList);
                // 栏目名称
//                ActivityColumn activityColumn = activityColumnMapper.selectByPrimaryKey(productModelResponse.getColumnId());
//                if (activityColumn != null) {
//                    productModelResponse.setActivityColumnName(activityColumn.getTitle());
//                }

                // 商品类型
                productModelResponse.setActivityTypeName(ActivityTypeNameCode.getName(productModelResponse.getActivityType()));

                // 活动类型列表
                ProductActivityExample productActivityExample = new ProductActivityExample();
                productActivityExample.createCriteria().andProductIdEqualTo(productModelResponse.getId());
                List<ProductActivity> productActivitys = productActivityMapper.selectByExample(productActivityExample);

                // 所属专区列表
                List<ProductSpecialResponse> productSpecials = productSpecialDao.productSpecial(productModelResponse.getId());

                productModelResponse.setProductActivity(productActivitys);
                productModelResponse.setProductSpecials(productSpecials);

                // 测评类型
                if (productModelResponse.getIsZeroProduct() == 1 && productModelResponse.getStockEvaluation() == 0) {
                    productModelResponse.setEvaluationType(2);
                } else if (productModelResponse.getIsZeroProduct() == 1 && productModelResponse.getStockEvaluation() > 0) {
                    productModelResponse.setEvaluationType(1);
                } else {
                    productModelResponse.setEvaluationType(3);
                }
            }
        }
        return CommonPage.restPage(page);
    }



    @Override
    public CommonPage<ProductModelResponse> downloadList(ProductRequest productRequest) {
        List<Integer> productIdsList = new ArrayList<>();
        if (null != productRequest.getSubjectId() || null != productRequest.getLabelId()){
            productIdsList = channelProductService.getProductIds(productRequest.getSubjectId(), productRequest.getLabelId(), productRequest.getPlatformData());
            if (CollectionUtils.isEmpty(productIdsList)) return CommonPage.restPage(new ArrayList<>());
            productRequest.setProductIds(productIdsList);
        }
        if (null != productRequest.getSupplyProductLabelId()){
            List<Integer> supplyProductIds = channelProductService.getSupplyProductIds(productRequest.getSupplyProductLabelId());
            if (CollectionUtils.isEmpty(supplyProductIds)) return CommonPage.restPage(new ArrayList<>());
            productRequest.setSupplyProductIds(supplyProductIds);
        }

        if (!org.springframework.util.StringUtils.isEmpty(productRequest.getBuyer())){
            BankerRequest request1 = new BankerRequest();
            request1.setBuyer(productRequest.getBuyer());
            String json1 = JSON.toJSONString(request1);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/getBankerIdsByBankerMsg", json1, supplyApiConfig.getHeadsMap());
            List<Integer> bankerIds = JSONObject.parseArray(result, Integer.class);
            if (CollectionUtils.isEmpty(bankerIds)){
                return CommonPage.restPage(new ArrayList<>());
            }
            productRequest.setBankerIds(bankerIds);
        }

        List<ProductModelResponse> page;
        List<String> provinceCodes = Optional.ofNullable(productRequest.getProvinceCodes()).orElse(new ArrayList<>()) ;
        List<String> requestProvinceCodes = new ArrayList<>();
        for (String provinceCode : provinceCodes) {
            requestProvinceCodes.add(PlatformConstant.PROVINCE_PLATFORM+provinceCode);
        }
        if(!CollectionUtils.isEmpty(requestProvinceCodes)){
            productRequest.setProvinceCodes(requestProvinceCodes);
        }
        if (null != productRequest.getArray() && 0 != productRequest.getArray().length) {
            page = productDao.selectListById(productRequest.getArray(),productRequest.getPlatformData());
        } else {
            page = productDao.selectList(productRequest);
        }

        List<Integer> specialIdList = page.stream().filter(item -> null != item.getSpecialId()).map(ProductModelResponse::getSpecialId).collect(Collectors.toList());
        List<Special> specials = new ArrayList<>();
        if (!CollectionUtils.isEmpty(specialIdList)){
            SpecialExample specialExample = new SpecialExample();
            specialExample.createCriteria().andIdIn(specialIdList);
            specials = specialMapper.selectByExample(specialExample);
        }

        List<Integer> columnIdList = page.stream().filter(item -> null != item.getColumnId()).map(ProductModelResponse::getColumnId).collect(Collectors.toList());
        List<ActivityColumn> activityColumns = new ArrayList<>();
        if (!CollectionUtils.isEmpty(columnIdList)){
            ActivityColumnExample activityColumnExample = new ActivityColumnExample();
            activityColumnExample.createCriteria().andIdIn(columnIdList);
            activityColumns = activityColumnMapper.selectByExample(activityColumnExample);
        }


        List<Integer> brandIdList = page.stream().filter(item -> null != item.getBrandId()).map(ProductModelResponse::getBrandId).collect(Collectors.toList());
        List<ProductBrand> productBrands = new ArrayList<>();
        if (!CollectionUtils.isEmpty(brandIdList)){
            ProductBrandExample productBrandExample = new ProductBrandExample();
            productBrandExample.createCriteria().andIdIn(brandIdList);
            productBrands = productBrandMapper.selectByExample(productBrandExample);
        }

        if (!CollectionUtils.isEmpty(page)) {

            //供应商id
            List<Integer> bankerIds = page.stream().filter(item ->null != item.getBankerId()).map(ProductModelResponse::getBankerId).collect(Collectors.toList());
            //查询供应商名称
            BankerRequest bankerRequest = new BankerRequest();
            bankerRequest.setBankerIdList(bankerIds);
            String json = JSON.toJSONString(bankerRequest);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getBankerMsg", json, supplyApiConfig.getHeadsMap());
            List<BankerResponse> bankerResponses = JSONObject.parseArray(result, BankerResponse.class);

//            List<ProductCategory> productCategoryAllList = productCategoryMapper.selectByExample(new ProductCategoryExample());
            List<ProductCategory> productCategoryAllList = channelProductService.getAllProductCategorys();
            List<ProductImg> imgInfoListAll = new ArrayList<>();

            // 活动类型列表
            ProductActivityExample productActivityExample = new ProductActivityExample();
            List<ProductActivity> productActivitysAll = productActivityMapper.selectByExample(productActivityExample);

            //查找该商品所属专题
            List<Integer> productIdList = page.stream().map(ProductModelResponse::getId).collect(Collectors.toList());
            List<ProductSubjectPlateResponse> productSubjectList = productSubjectPlateDao.findAllByProductIds(productIdList);
            Map<Integer, List<ProductSubjectPlateResponse>> listMap =
                    productSubjectList.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(ProductSubjectPlateResponse::getProductId));
            for (ProductModelResponse item : page) {
                List<BankerResponse> bankerResponse = bankerResponses.stream().filter(banker -> banker.getBankerId().equals(item.getBankerId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(bankerResponse)){
                    //采购员
                    item.setBuyer(bankerResponse.get(0).getBuyer());
                }
                for (Integer productId : listMap.keySet()) {
                    if (item.getId().equals(productId)) {
                        item.setSubjectName(listMap.get(productId).stream().map(ProductSubjectPlateResponse::getSubjectName).collect(Collectors.joining(",")));
                    }
                }
            }

            // 所有专区列表
            List<ProductSpecialResponse> productSpecialsAll = productSpecialDao.productSpecial(null);
            for (ProductModelResponse productModelResponse : page) {
                productModelResponse.setPrice(Optional.ofNullable(productModelResponse.getPrice()).orElse(BigDecimal.ZERO));
                productModelResponse.setOriginalPrice(Optional.ofNullable(productModelResponse.getOriginalPrice()).orElse(BigDecimal.ZERO));
                if (null == productModelResponse.getWxProductId()) {
                    productModelResponse.setWxProductFlag(0);
                }else {
                    productModelResponse.setWxProductFlag(productModelResponse.getWxProductId() > 0 ? 1 : 0);
                }
                if (!CollectionUtils.isEmpty(specials) && null != productModelResponse.getSpecialId()){
                    List<Special> collect = specials.stream().filter(item -> item.getId().equals(productModelResponse.getSpecialId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)){
                        productModelResponse.setSpecialName(collect.get(0).getTitle());
                    }
                }
                if (!CollectionUtils.isEmpty(activityColumns) && null != productModelResponse.getColumnId()){
                    List<ActivityColumn> collect = activityColumns.stream().filter(item -> item.getId().equals(productModelResponse.getColumnId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)){
                        productModelResponse.setActivityColumnName(collect.get(0).getTitle());
                    }
                }
                if (!CollectionUtils.isEmpty(productBrands) && null != productModelResponse.getBrandId()){
                    List<ProductBrand> collect = productBrands.stream().filter(item -> item.getId().equals(productModelResponse.getBrandId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)){
                        productModelResponse.setBrandName(collect.get(0).getBrandName());
                    }
                }



                // 产品分类
                productCategoryAllList.stream().forEach(s -> {
                    if (null != productModelResponse.getTopCategoryId() && productModelResponse.getTopCategoryId().equals(s.getId())) {
                        productModelResponse.setCategoryTopTitle(s.getTitle());
                    }
                    if (null != productModelResponse.getCategoryId() && productModelResponse.getCategoryId().equals(s.getId())) {
                        productModelResponse.setCategoryTitle(s.getTitle());
                    }
                    if (null != productModelResponse.getBottomCategoryId() && productModelResponse.getBottomCategoryId().equals(s.getId())) {
                        productModelResponse.setCategoryBottomTitle(s.getTitle());
                    }
                });
                List<ProductImg> imgInfoList = imgInfoListAll;
                List<ProductImg> bannerList = new ArrayList<>();
                List<ProductImg> infoList = new ArrayList<>();
                imgInfoList.stream().forEach(s -> {
                    if ("banner".equals(s.getType())) {
                        bannerList.add(s);
                    }
                    if ("info".equals(s.getType())) {
                        infoList.add(s);
                    }
                });
                productModelResponse.setBannerImgList(bannerList);
                productModelResponse.setDetailList(infoList);

                //活动类型
                productModelResponse.setActivityType(ActivityEnums.getName(productModelResponse.getActivityType()));

                // 毛利率
                BigDecimal price = null == productModelResponse.getPrice() ? BigDecimal.ZERO : productModelResponse.getPrice();
                BigDecimal costPrice = productModelResponse.getCostPrice();
                BigDecimal grossProfit = new BigDecimal(0);
                String grossProfixRate = "0.00";
                if (null != price && price.compareTo(BigDecimal.ZERO) != 0 ) {
                    grossProfit = price.subtract(Optional.ofNullable(costPrice).orElse(BigDecimal.ZERO)).divide(price, 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                    DecimalFormat df = new DecimalFormat("0.00");
                    grossProfixRate = df.format(grossProfit);
                }
                productModelResponse.setGrossProfitRate(grossProfixRate);

                // 补贴力度
                BigDecimal subsidy = null == productModelResponse.getOriginalPrice() ? BigDecimal.ZERO : productModelResponse.getOriginalPrice().subtract(productModelResponse.getPrice());
                productModelResponse.setSubsidy(subsidy.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : subsidy);

                // 商品类型
                productModelResponse.setActivityTypeName(ActivityTypeNameCode.getName(productModelResponse.getActivityType()));

                // 活动类型列表
                List<ProductActivity> productActivitys = productActivitysAll.stream().filter(s -> s.getProductId().equals(productModelResponse.getId())).collect(Collectors.toList());

                // 所属专区列表
                List<ProductSpecialResponse> productSpecials = productSpecialsAll.stream().filter(s -> s.getProductId().equals(productModelResponse.getId())).collect(Collectors.toList());//productSpecialDao.productSpecial(productModelResponse.getId());

                productModelResponse.setProductActivity(productActivitys);
                productModelResponse.setProductSpecials(productSpecials);

                // 测评类型
                if (productModelResponse.getIsZeroProduct() == 1 && productModelResponse.getStockEvaluation() == 0) {
                    productModelResponse.setEvaluationType(2);
                } else if (productModelResponse.getIsZeroProduct() == 1 && productModelResponse.getStockEvaluation() > 0) {
                    productModelResponse.setEvaluationType(1);
                } else {
                    productModelResponse.setEvaluationType(3);
                }

            }
            productCategoryAllList = null;
            imgInfoListAll = null;
            // 活动类型列表
            productActivitysAll = null;
            // 所有专区列表
            productSpecialsAll = null;

            List<ProductSpecStockQureyResponse> productSpecStockQureyResponses = new ArrayList<>();
//            try {
//                //获取规格库存
//                List<Integer> supplyIds = page.stream().filter(item -> null != item.getSupplyId()).map(ProductModelResponse::getSupplyId).collect(Collectors.toList());
//                if (!CollectionUtils.isEmpty(supplyIds)){
//                    ProductSpecStockQureyRequest productSpecStockQureyRequest = new ProductSpecStockQureyRequest();
//                    productSpecStockQureyRequest.setSupplyIds(supplyIds);
//                    String reultJson = JSON.toJSONString(productSpecStockQureyRequest);
//                    String doPostJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getSpecStock", reultJson, supplyApiConfig.getHeadsMap());
//                    if (!org.springframework.util.StringUtils.isEmpty(doPostJson)){
//                        productSpecStockQureyResponses = JSONObject.parseArray(doPostJson, ProductSpecStockQureyResponse.class);
//                        List<ProductSpecStockQureyResponse> finalProductSpecStockQureyResponses = productSpecStockQureyResponses;
//                        page.stream().forEach(item ->{
//                            List<ProductSpecStockQureyResponse> collect = finalProductSpecStockQureyResponses.stream().filter(productSpecStockQureyResponse -> productSpecStockQureyResponse.getSupplyId().equals(item.getSupplyId())).collect(Collectors.toList());
//                            if (!CollectionUtils.isEmpty(collect)) {
//                                ProductSpecStockQureyResponse productSpecStockQureyResponse = collect.get(0);
//                                item.setSpecStock(productSpecStockQureyResponse.getStock());
//                            }
//                        });
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            /**
             * 是否多规格显示
             */
            if (moreSpec.equals(1)) {
                List<Integer> productIds = page.stream().map(ProductModelResponse::getId).collect(Collectors.toList());
                List<ProductSpec> productSpecList = productSpecDao.selectByProductIds(productIds);
                List<Integer> supplyIds = productSpecList.stream().filter(item -> null != item.getSupplyId()).map(ProductSpec::getSupplyId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(supplyIds)){
                    ProductSpecStockQureyRequest productSpecStockQureyRequest = new ProductSpecStockQureyRequest();
                    productSpecStockQureyRequest.setSupplyIds(supplyIds);
                    String reultJson = JSON.toJSONString(productSpecStockQureyRequest);
                    String doPostJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getSpecStock", reultJson, supplyApiConfig.getHeadsMap());
                    if (!org.springframework.util.StringUtils.isEmpty(doPostJson)){
                        productSpecStockQureyResponses = JSONObject.parseArray(doPostJson, ProductSpecStockQureyResponse.class);
//                        List<ProductSpecStockQureyResponse> finalProductSpecStockQureyResponses = productSpecStockQureyResponses;
//                        page.stream().forEach(item ->{
//                            List<ProductSpecStockQureyResponse> collect = finalProductSpecStockQureyResponses.stream().filter(productSpecStockQureyResponse -> productSpecStockQureyResponse.getSupplyId().equals(item.getSupplyId())).collect(Collectors.toList());
//                            if (!CollectionUtils.isEmpty(collect)) {
//                                ProductSpecStockQureyResponse productSpecStockQureyResponse = collect.get(0);
//                                item.setSpecStock(productSpecStockQureyResponse.getStock());
//                            }
//                        });
                    }
                }
                List<ProductSpecStockQureyResponse> finalProductSpecStockQureyResponses1 = productSpecStockQureyResponses;
                productSpecList.forEach(item ->{
                    Optional<ProductSpecStockQureyResponse> first = finalProductSpecStockQureyResponses1.stream().filter(e -> e.getSupplyId().equals(item.getSupplyId())).findFirst();
                    first.ifPresent(productModelResponse -> item.setStock(productModelResponse.getStock()));
                });
                page.stream().forEach(product -> {
                    List<ProductSpec> matchSpecs = productSpecList.stream().filter(spec -> spec.getProductId().equals(product.getId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(matchSpecs)) {
                        ProductSpec matchSpec = matchSpecs.get(0);
                        product.setProductSpecId(matchSpec.getId());
                        product.setSpecSkuSpec(matchSpec.getSkuSpec());
                        product.setSpecPrice(matchSpec.getPrice());
                        product.setSpecCostPrice(matchSpec.getCostPrice());
                        product.setSpecStock(Optional.ofNullable(matchSpec.getStock()).orElse(0));
                        product.setSpecSupplyPrice(matchSpec.getSupplyPrice());
                        product.setSpecCurPrice(matchSpec.getCurPrice());
                        product.setMarketPrice(matchSpec.getMarketPrice());
                        product.setSpecOriginalPrice(matchSpec.getOriginalPrice());
                        product.setSpecSalePrice(matchSpec.getSalePrice());
                        productSpecList.remove(matchSpec);
                    }
                });
                productSpecList.stream().forEach(spec -> {
                    ProductModelResponse response = new ProductModelResponse();
                    response.setId(spec.getProductId());
                    response.setProductSpecId(spec.getId());
                    response.setSpecSkuSpec(spec.getSkuSpec());
                    response.setSpecPrice(spec.getPrice());
                    response.setSpecCostPrice(spec.getCostPrice());
                    response.setSpecStock(Optional.ofNullable(spec.getStock()).orElse(0));
                    response.setSpecSupplyPrice(spec.getSupplyPrice());
                    response.setSpecCurPrice(spec.getCurPrice());
                    response.setSupplyId(spec.getSupplyId());
                    response.setMarketPrice(spec.getMarketPrice());
                    response.setSpecOriginalPrice(spec.getOriginalPrice());
                    response.setSpecSalePrice(spec.getSalePrice());
                    page.add(response);
                });
                productIds = null;

            }


        }
//        page.stream().sorted((stu1, stu2) -> Long.compare(stu2.getId(), stu1.getId()));
        return CommonPage.restPage(page.stream().sorted((stu1, stu2) -> Long.compare(stu2.getId(), stu1.getId())).collect(Collectors.toList()));
    }

    @Override
    public List<Product> getListByBankerId(Integer bankerId) {
        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andBankerIdEqualTo(bankerId);
        return productMapper.selectByExample(productExample);
    }

    @Override
    public Product productInfosById(Integer id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int create(AddProductRequest addProductRequest) {

        // 校验店家是否存在
        Banker banker = bankerMapper.selectByPrimaryKey(addProductRequest.getBankerId());
        if (banker == null) {
            throw new ApiException("该店家id{" + addProductRequest.getBankerId() + "}不存在！");
        }

        // 处理数据
        // 属性value id 集合
        List<Integer> attributeValueIds = addProductRequest.getAttributeValueIds();
        if (attributeValueIds.size() <= 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.SKU_ATTRIBUTE_CANT_NULL));
        }

        // 根据选择的属性value id集合转化数据
        List<Map<String, Object>> list = this.getCheckedSpan(attributeValueIds);
        if (list.size() > 2) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.SKU_ATTRIBUTE_CANT_TOW_KEY));
        }

        String specJson = JSON.toJSONString(list);

        // 商品编号
        String productNo = OrderUtils.getProductNo();
        addProductRequest.setId(null);
        addProductRequest.setProductNo(productNo);
        addProductRequest.setAttributeJson(specJson);
        addProductRequest.setStock(0);
        // 商品状态默认下架
        addProductRequest.setStatus(SysConfigConstants.Product_Status.STATUS_2);
        addProductRequest.setCreateTime(new Date());
        if (addProductRequest.getBankerColumnId().equals(3)) {
            addProductRequest.setIsZeroProduct(1);
        }
        int count = productMapper.insertSelective(addProductRequest);

        // 新增商品规格表
        List<String> sku_spec = this.getDetailByJson(specJson);
        if (!CollectionUtils.isEmpty(sku_spec)) {
            for (String skuSpec : sku_spec) {
                ProductSpec productSpec = new ProductSpec();
                productSpec.setProductId(addProductRequest.getId());
                productSpec.setSkuSpec(skuSpec);
                productSpec.setCurPrice(addProductRequest.getCurPrice());
                productSpec.setPrice(addProductRequest.getPrice());
                productSpec.setProImg(addProductRequest.getProductImg());
                productSpec.setBuySum(addProductRequest.getVolume());
                productSpec.setStock(0);
                productSpec.setStatus(SysConfigConstants.STATUS_1);
                productSpec.setCreateTime(new Date());
                productSpecMapper.insert(productSpec);
            }
        }

        Map<Integer, Object> param = new HashMap<>();

        // 新增商品sku属性key-value表数据
        for (Integer attributeValueId : attributeValueIds) {

            ProductAttributeValue productAttributeValue = productAttributeValueMapper.selectByPrimaryKey(attributeValueId);
            ProductAttributeKey productAttributeKey = productAttributeKeyMapper.selectByPrimaryKey(productAttributeValue.getAttributeId());

            // 新增sku属性key
            if (param.get(productAttributeKey.getId()) == null) {
                ProductSkuKey productSkuKey = new ProductSkuKey();
                productSkuKey.setPid(addProductRequest.getId());
                productSkuKey.setKid(productAttributeKey.getId());
                productSkuKey.setSort(productAttributeKey.getSort());
                productSkuKey.setName(productAttributeKey.getAttributeName());
                productSkuKey.setCreateTime(new Date());
                productSkuKeyMapper.insert(productSkuKey);
                param.put(productAttributeKey.getId(), productSkuKey);
            }

            // 新增sku属性value
            ProductSkuValue productSkuValue = new ProductSkuValue();
            productSkuValue.setPid(addProductRequest.getId());
            productSkuValue.setVid(attributeValueId);
            productSkuValue.setValue(productAttributeValue.getAttributeValue());
            productSkuValue.setSort(productAttributeValue.getSort());
            productSkuValue.setStatus(SysConfigConstants.STATUS_1);
            productSkuValue.setCreateTime(new Date());
            productSkuValueMapper.insert(productSkuValue);
        }

        // 新增商品推荐信息
        ProductMatching productMatching = new ProductMatching();
        productMatching.setProductId(addProductRequest.getId());
        productMatching.setCreateTime(new Date());
        productMatchingMapper.insertSelective(productMatching);

        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(EditProductRequest editProductRequest) {
        if (null != editProductRequest.getBankerColumnId() && editProductRequest.getBankerColumnId().equals(3)) {
            if (!"".equals(editProductRequest.getActivityType())) {
                throw new ApiException("该商品已添加到运营活动，不能新增到0元测评");
            }
        }

        // 属性value id 集合
//        List<Integer> attributeValueIds = editProductRequest.getAttributeValueIds();
//        if (attributeValueIds.size() <= 0) {
//            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.SKU_ATTRIBUTE_CANT_NULL));
//        }
//
//        // 判断suk属性的key值是否跟新增一致
//        List<Map<String, Object>> list = this.getCheckedSpan(attributeValueIds);
//
//        ProductSkuKeyExample productSkuKeyExample = new ProductSkuKeyExample();
//        productSkuKeyExample.createCriteria().andPidEqualTo(editProductRequest.getId());
//        List<ProductSkuKey> productSkuKeys = productSkuKeyMapper.selectByExample(productSkuKeyExample);
//        if (productSkuKeys.size() != list.size()) {
//            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.SKU_ATTRIBUTE_ATYPISM));
//        }
//
//        String specJson = JSON.toJSONString(list);
        // 改变商品规格的 sku属性值
//        Product product = new Product();
//        product.setId(editProductRequest.getId());
//        //product.setAttributeJson(specJson);
//        // product.setBottomCategoryId(editProductRequest.getBottomCategoryId());
//        productMapper.updateByPrimaryKeySelective(product);

        // 新增/停用 商品属性规格表

        // 先停用所有商品属性规格表
//        ProductSpecExample productSpecExample = new ProductSpecExample();
//        productSpecExample.createCriteria().andProductIdEqualTo(editProductRequest.getId());
//        List<ProductSpec> productSpecs = productSpecMapper.selectByExample(productSpecExample);
//        if (!CollectionUtils.isEmpty(productSpecs)) {
//            for (ProductSpec productSpec : productSpecs) {
//                productSpec.setStatus(SysConfigConstants.STATUS_0);
//                productSpecMapper.updateByPrimaryKeySelective(productSpec);
//            }
//        }
//
//        List<String> sku_spec = this.getDetailByJson(specJson);
//        if (!CollectionUtils.isEmpty(sku_spec)) {
//            for (String skuSpec : sku_spec) {
//                ProductSpecExample pse = new ProductSpecExample();
//                pse.createCriteria().andProductIdEqualTo(editProductRequest.getId()).andSkuSpecEqualTo(skuSpec);
//                List<ProductSpec> psList = productSpecMapper.selectByExample(pse);
//                if (!CollectionUtils.isEmpty(psList)) {
//                    ProductSpec productSpec = psList.get(0);
//                    productSpec.setStatus(SysConfigConstants.STATUS_1);
//                    productSpecMapper.updateByPrimaryKeySelective(productSpec);
//                } else {
//                    ProductSpec data = new ProductSpec();
//                    data.setProductId(editProductRequest.getId());
//                    data.setSkuSpec(skuSpec);
//                    data.setCurPrice(editProductRequest.getCurPrice());
//                    data.setPrice(editProductRequest.getPrice());
//                    data.setProImg(editProductRequest.getProductImg());
//                    data.setBuySum(editProductRequest.getVolume());
//                    data.setStock(0);
//                    data.setStatus(SysConfigConstants.STATUS_1);
//                    data.setCreateTime(new Date());
//                    productSpecMapper.insertSelective(data);
//                }
//            }
//        }
//        // 清空商品sku属性key-value表数据
//        ProductSkuKeyExample pske = new ProductSkuKeyExample();
//        pske.createCriteria().andPidEqualTo(editProductRequest.getId());
//        List<ProductSkuKey> skuKeys = productSkuKeyMapper.selectByExample(pske);
//        if (!CollectionUtils.isEmpty(skuKeys)) {
//            for (ProductSkuKey productSkuKey : skuKeys) {
//                productSkuKeyMapper.deleteByPrimaryKey(productSkuKey.getId());
//            }
//        }
//        ProductSkuValueExample psve = new ProductSkuValueExample();
//        psve.createCriteria().andPidEqualTo(editProductRequest.getId());
//        List<ProductSkuValue> skuValues = productSkuValueMapper.selectByExample(psve);
//        if (!CollectionUtils.isEmpty(skuValues)) {
//            for (ProductSkuValue productSkuValue : skuValues) {
//                productSkuValueMapper.deleteByPrimaryKey(productSkuValue.getId());
//            }
//        }
//
//
//        // 更新商品sku属性key-value表数据
//        Map<Integer, Object> param = new HashMap<>();
//
//        for (Integer attributeValueId : attributeValueIds) {
//
//            ProductAttributeValue productAttributeValue = productAttributeValueMapper.selectByPrimaryKey(attributeValueId);
//            ProductAttributeKey productAttributeKey = productAttributeKeyMapper.selectByPrimaryKey(productAttributeValue.getAttributeId());
//
//            // 新增sku属性key
//            if (param.get(productAttributeKey.getId()) == null) {
//                ProductSkuKey productSkuKey = new ProductSkuKey();
//                productSkuKey.setPid(editProductRequest.getId());
//                productSkuKey.setKid(productAttributeKey.getId());
//                productSkuKey.setSort(productAttributeKey.getSort());
//                productSkuKey.setName(productAttributeKey.getAttributeName());
//                productSkuKey.setCreateTime(new Date());
//                productSkuKeyMapper.insert(productSkuKey);
//                param.put(productAttributeKey.getId(), productSkuKey);
//            }
//
//            // 新增sku属性value
//            ProductSkuValue productSkuValue = new ProductSkuValue();
//            productSkuValue.setPid(editProductRequest.getId());
//            productSkuValue.setVid(attributeValueId);
//            productSkuValue.setValue(productAttributeValue.getAttributeValue());
//            productSkuValue.setSort(productAttributeValue.getSort());
//            productSkuValue.setStatus(SysConfigConstants.STATUS_1);
//            productSkuValue.setCreateTime(new Date());
//            productSkuValueMapper.insert(productSkuValue);
//        }
        editProductRequest.setIsZeroProduct(0);
        // 如果是零元测评商品
        if (null != editProductRequest.getBankerColumnId() && editProductRequest.getBankerColumnId().equals(3)) {
            editProductRequest.setIsZeroProduct(1);
        } else {
            //不是零元测评商品时，助力人数设置为0
            editProductRequest.setHelpNum(0);
        }
        editProductRequest.setUpdateTime(new Date());
        editProductRequest.setOriginalPrice(null);
        editProductRequest.setPrice(null);
        return productMapper.updateByPrimaryKeySelective(editProductRequest);
    }

    @Override
    public Map<String, Object> selectSkuKeysbyId(Integer id) {

        Map<String, Object> map = new HashMap<>();

        // 查询商品选择的属性 key 集合
        ProductSkuKeyExample productSkuKeyExample = new ProductSkuKeyExample();
        productSkuKeyExample.createCriteria().andPidEqualTo(id);
        List<ProductSkuKey> productSkuKeys = productSkuKeyMapper.selectByExample(productSkuKeyExample);

        // 查询商品选择的属性 value 集合
        ProductSkuValueExample productSkuValueExample = new ProductSkuValueExample();
        productSkuValueExample.createCriteria().andPidEqualTo(id);
        List<ProductSkuValue> productSkuValues = productSkuValueMapper.selectByExample(productSkuValueExample);
        List<Integer> checkedIds = productSkuValues.stream().map(ProductSkuValue::getVid).collect(Collectors.toList());

        // 查询选择的属性key的所有value集合
        List<Map<String, Object>> spec_array = new ArrayList<>();
        if (!CollectionUtils.isEmpty(productSkuKeys)) {
            List<Integer> attributeKeyIds = productSkuKeys.stream().map(ProductSkuKey::getKid).collect(Collectors.toList());
            for (Integer attributeKeyId : attributeKeyIds) {
                Map<String, Object> spec_map = new LinkedHashMap<>();
                Map<String, Object> spanKeys_map = new LinkedHashMap<>();
                ProductAttributeKey productAttributeKey = productAttributeKeyMapper.selectByPrimaryKey(attributeKeyId);
                ProductAttributeValueExample productAttributeValueExample = new ProductAttributeValueExample();
                productAttributeValueExample.createCriteria().andAttributeIdEqualTo(productAttributeKey.getId());
                List<ProductAttributeValue> productAttributeValues = productAttributeValueMapper.selectByExample(productAttributeValueExample);
                spanKeys_map.put("id", "p" + productAttributeKey.getId());
                spanKeys_map.put("name", productAttributeKey.getAttributeName());
                spec_map.put("spanName", spanKeys_map);
                if (!CollectionUtils.isEmpty(productAttributeValues)) {
                    List<Map<String, Object>> spanValues = new ArrayList<>();
                    for (ProductAttributeValue productAttributeValue : productAttributeValues) {
                        Map<String, Object> spanValues_map = new HashMap<>();
                        spanValues_map.put("id", productAttributeValue.getId());
                        spanValues_map.put("name", productAttributeValue.getAttributeValue());
                        spanValues.add(spanValues_map);
                    }
                    spec_map.put("spanValue", spanValues);
                }
                spec_array.add(spec_map);
            }
        }
        map.put("checkeds", checkedIds);
        map.put("keys", spec_array);
        return map;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStatus(Integer id, Byte status, String downRemark) {
        // 上下架状态 1-上架 2-下架 3-已删除 4-待上架 5-打回
        com.ytjj.qmyx.mall.model.Product product = productMapper.selectByPrimaryKey(id);

//        //上架时需要校验商品对应的供应商是否已下架
//        boolean bankerStatus = checkBankerStatus(product.getBankerId());
//        if (status == 1 && !bankerStatus) {
//            throw new ApiException("供应商已下架，不能上架该商品");
//        }
//        //上架时需要校验商品对应的供应商品牌是否已下架
//        boolean bankerBrandStatus = checkBankerBrandStatus(product.getBankerProductId());
//        if (status == 1 && !bankerBrandStatus) {
//            throw new ApiException("供应商品牌已下架，不能上架该商品");
//        }
//        boolean bankerAuditStatus = checkBankeAuditStatus(product.getBankerProductId());
//        if (status == 1 && !bankerAuditStatus) {
//            throw new ApiException("商品审核未通过，不能上架该商品");
//        }

        if (status == 1) {
            channelProductService.getSupplyProductStatus(product);
        }

        product.setStatus(status);
        if (status == 2) {
            //下架时备注下架原因
            product.setDownRemark(downRemark);
        } else {
            product.setDownRemark("");
        }
        product.setUpdateTime(new Date());
        //上架/下架所有专区的商品
        ProductSpecialExample productSpecialExample = new ProductSpecialExample();
        productSpecialExample.createCriteria().andProductIdEqualTo(id);
        List<ProductSpecial> productSpecials = productSpecialMapper.selectByExample(productSpecialExample);
        if (status == 3 && !CollectionUtils.isEmpty(productSpecials)) {
            for (ProductSpecial productSpecial : productSpecials) {
                productSpecial.setStatus((byte) 2);
                productSpecial.setUpdateTime(new Date());
                productSpecialMapper.updateByPrimaryKeySelective(productSpecial);
            }
        } else if (!CollectionUtils.isEmpty(productSpecials)) {
            for (ProductSpecial productSpecial : productSpecials) {
                productSpecial.setStatus(status);
                productSpecial.setUpdateTime(new Date());
                productSpecialMapper.updateByPrimaryKeySelective(productSpecial);
            }

        }
//        //商品上架时，供应商商品数+1，下架时商品数-1
//        if (status == 1) {
//            bankerDao.addProductNum(product.getBankerId());
//            product.setUpTime(new Date());
//        }
//        if (status == 2) {
//            bankerDao.subProductNum(product.getBankerId());
//        }

//        // 商品上下架 消息通知
//        BankerMessage message = new BankerMessage();
//        message.setBankerId(product.getBankerId());
//        message.setBankerProductId(product.getBankerProductId());
//        message.setProductName(product.getProductName());
//        message.setStatus(0);
//        message.setCreateTime(new Date());
//        if (status == 1) {
//            message.setRemarks("您的商品：" + product.getProductName() + " 已上架！");
//            message.setType(3);
//            bankerMessageDao.insertMessage(message);
//        } else if (status == 2) {
//            message.setRemarks("您的商品：" + product.getProductName() + " 已被下架，原因:(" + downRemark + ")");
//            message.setType(4);
//            bankerMessageDao.insertMessage(message);
//        } else {
//            // 删除时 不作处理
//        }

//        //将普通商品的上下架状态同步至供应商商品中
//        if (status == 3) {
//            bankerProductDao.updateStatus(product.getBankerProductId(), 2);
//        } else {
//            bankerProductDao.updateStatus(product.getBankerProductId(), status.intValue());
//        }
        if (status == 1) {
            product.setUpTime(new Date());
        }
        return productMapper.updateByPrimaryKeySelective(product);
    }


    private boolean checkBankeAuditStatus(Integer bankerProductId) {
        if (null == bankerProductId) {
            return false;
        }
        BankerProduct bankerProduct = bankerProductDao.getBankerProduct(bankerProductId);
        if (null == bankerProduct) {
            return false;
        }
        //审核状态 0 未审核 1 通过 2 不通过
        if (1 != bankerProduct.getAuditStatus()) {
            return false;
        }
        return true;
    }

    private boolean checkBankerBrandStatus(Integer bankerProductId) {
        if (null == bankerProductId) {
            return true;
        }
        BankerProduct bankerProduct = bankerProductDao.getBankerProduct(bankerProductId);
        if (null == bankerProduct) {
            return true;
        }
        BankerBrand bankerBrand = bankerBrandService.selectById(bankerProduct.getBrandId());
        if (null == bankerBrand) {
            return true;
        }
        if (1 != bankerBrand.getPutOn()) {
            return false;
        }
        return true;
    }

    private boolean checkBankerStatus(Integer bankerId) {
        if (null == bankerId) {
            return true;
        }
        Banker banker = bankerMapper.selectByPrimaryKey(bankerId);
        if (null == banker) {
            return true;
        }
        if (1 != (null == banker.getStatus() ? 0 : banker.getStatus().intValue())) {
            return false;
        }
        return true;
    }

    @Override
    public int delete(Integer id) {
        return productMapper.deleteByPrimaryKey(id);
    }

    // ---------------------------------------------------------------添加活动-----------------------------------------------------------------------------------

    @Override
    public int addActivity(ProductActivityRequest productActivity) {

        List<Integer> attributeValueIds = productActivity.getAttributeValueIds();
        if (CollectionUtils.isEmpty(attributeValueIds)) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.SKU_ATTRIBUTE_CANT_NULL));
        }

        // 根据选择的属性value id集合转化数据
        List<Map<String, Object>> list = this.getCheckedSpan(attributeValueIds);
        if (list.size() > 2) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.SKU_ATTRIBUTE_CANT_TOW_KEY));
        }

        String specJson = JSON.toJSONString(list);

        com.ytjj.qmyx.mall.model.Product product = productMapper.selectByPrimaryKey(productActivity.getProductId());
        if (product == null) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST));
        }

        // set 属性
        productActivity.setDescr(product.getDescr());
        productActivity.setProductNo(product.getProductNo());
        productActivity.setProductImg(product.getProductImg());
        productActivity.setProductName(product.getProductName());
        productActivity.setSceneImg(product.getSceneImg());
        productActivity.setWarehouse(product.getWarehouse());
        productActivity.setWarehouseName(product.getWarehouseName());
        productActivity.setWarehouseRule(product.getWarehouseRule());
        // sku 属性json列表
        productActivity.setAttributeJson(specJson);
        productActivity.setDataType(productActivity.getDataType());

        productActivity.setPv(product.getPv());
        productActivity.setComment(product.getCommentSum());
        if (product.getGoodRatio() != null) {
            productActivity.setCommentGood(BigDecimal.valueOf(product.getGoodRatio()));
        }
        productActivity.setSort(product.getSort());
        productActivity.setVolume(product.getVolume());
        productActivity.setCost(product.getCostPrice());
        // productActivity.setVolumeStr(product.getVolumeStr());   销售展示
        productActivity.setStock(product.getStock());        // 总库存
        productActivity.setStatus(SysConfigConstants.Activity_Status.STATUS_2);
        productActivity.setOriginalPrice(product.getOriginalPrice());
        productActivity.setBankerId(product.getBankerId());
        // productActivity.setPrice(product.getPrice());
        productActivity.setRecImgFlag(product.getRecImgFlag());
        productActivity.setCreateTime(new Date());

        productActivity.setCurPrice(product.getCurPrice());
        productActivity.setRecommendDoc(product.getRecommendDoc());
        productActivity.setRecDescr(product.getRecDescr());
        productActivity.setIsAdvert(productActivity.getIsAdvert());
        productActivity.setIsHide(productActivity.getIsHide());
        productActivity.setBrandId(productActivity.getBrandId());
        productActivity.setLongTitle(product.getLongTitle());
        productActivity.setBankerProductId(product.getBankerProductId());
        productActivity.setEvaluationProductId(product.getEvaluationProductId());
        productActivity.setPlatformData(productActivity.getPlatformData());
        int count = productActivityMapper.insertSelective(productActivity);

        // 商品图片带到活动商品图片
        ProductImgExample productImgExample = new ProductImgExample();
        productImgExample.createCriteria().andProductIdEqualTo(productActivity.getProductId());
        List<ProductImg> productImgs = productImgMapper.selectByExample(productImgExample);
        if (!CollectionUtils.isEmpty(productImgs)) {
            for (ProductImg productImg : productImgs) {
                ProductActivityImg productActivityImg = new ProductActivityImg();
                productActivityImg.setProductId(productActivity.getId());
                productActivityImg.setImgUrl(productImg.getImgUrl());
                productActivityImg.setSort(productImg.getSort());
                productActivityImg.setType(productImg.getType());
                productActivityImg.setFileType(productImg.getFileType());
                productActivityImg.setCreateTime(new Date());
                productActivityImgMapper.insert(productActivityImg);
            }
        }


        // 新增商品规格表
        ProductSpecExample productSpecExample = new ProductSpecExample();
        productSpecExample.createCriteria().andProductIdEqualTo(productActivity.getProductId())
                .andStatusEqualTo((byte) 1);
        List<ProductSpec> productSpecs = productSpecMapper.selectByExample(productSpecExample);
        if (!CollectionUtils.isEmpty(productSpecs)) {
            for (ProductSpec productSpec : productSpecs) {
                ProductActivitySpec productActivitySpec = new ProductActivitySpec();
                productActivitySpec.setActivityId(productActivity.getId());
                productActivitySpec.setSkuSpec(productSpec.getSkuSpec());
                productActivitySpec.setCurPrice(productSpec.getCurPrice());
                productActivitySpec.setPrice(productActivity.getPrice());
                productActivitySpec.setProImg(productSpec.getProImg());
                productActivitySpec.setBuySum(product.getVolume());
                productActivitySpec.setStock(productSpec.getStock());
                productActivitySpec.setCreateTime(new Date());
                productActivitySpec.setBankerProductId(productSpec.getBankerProductId());
                productActivitySpec.setEvaluationProductId(productSpec.getEvaluationProductId());
                productActivitySpecMapper.insert(productActivitySpec);
            }
        }

        /*//添加商品活动时，只把普通商品的spec规格同步过去，添加活动页面的规格选择--前端未隐藏但是后端不做处理
        List<String> sku_spec = this.getDetailByJson(specJson);
        if (!CollectionUtils.isEmpty(sku_spec)) {
            for (String skuSpec : sku_spec) {
                ProductActivitySpec productActivitySpec = new ProductActivitySpec();
                productActivitySpec.setActivityId(productActivity.getId());
                productActivitySpec.setSkuSpec(skuSpec);
                productActivitySpec.setPrice(productActivity.getPrice());
                productActivitySpec.setProImg(productActivity.getProductImg());
                productActivitySpec.setBuySum(productActivity.getVolume());
                productActivitySpec.setStock(0);
                productActivitySpec.setCreateTime(new Date());
                productActivitySpecMapper.insert(productActivitySpec);
            }
        }*/

        // 清空活动商品sku属性key-value表数据
        ProductActivitySkuKeyExample paske = new ProductActivitySkuKeyExample();
        paske.createCriteria().andPidEqualTo(productActivity.getId());
        List<ProductActivitySkuKey> skuKeys = productActivitySkuKeyMapper.selectByExample(paske);
        if (!CollectionUtils.isEmpty(skuKeys)) {
            for (ProductActivitySkuKey productActivitySkuKey : skuKeys) {
                productActivitySkuKeyMapper.deleteByPrimaryKey(productActivitySkuKey.getId());
            }
        }
        ProductActivitySkuValueExample pasve = new ProductActivitySkuValueExample();
        pasve.createCriteria().andPidEqualTo(productActivity.getId());
        List<ProductActivitySkuValue> skuValues = productActivitySkuValueMapper.selectByExample(pasve);
        if (!CollectionUtils.isEmpty(skuValues)) {
            for (ProductActivitySkuValue productActivitySkuValue : skuValues) {
                productActivitySkuValueMapper.deleteByPrimaryKey(productActivitySkuValue.getId());
            }
        }


        // 更新商品sku属性key-value表数据
        Map<Integer, Object> param = new HashMap<>();
        for (Integer attributeValueId : attributeValueIds) {

            ProductAttributeValue productAttributeValue = productAttributeValueMapper.selectByPrimaryKey(attributeValueId);
            ProductAttributeKey productAttributeKey = productAttributeKeyMapper.selectByPrimaryKey(productAttributeValue.getAttributeId());

            // 新增sku属性key
            if (param.get(productAttributeKey.getId()) == null) {
                ProductActivitySkuKey productActivitySkuKey = new ProductActivitySkuKey();
                productActivitySkuKey.setPid(productActivity.getId());
                productActivitySkuKey.setKid(productAttributeKey.getId());
                productActivitySkuKey.setSort(productAttributeKey.getSort());
                productActivitySkuKey.setName(productAttributeKey.getAttributeName());
                productActivitySkuKey.setCreateTime(new Date());
                productActivitySkuKeyMapper.insert(productActivitySkuKey);
                param.put(productAttributeKey.getId(), productActivitySkuKey);
            }

            // 新增sku属性value
            ProductActivitySkuValue productActivitySkuValue = new ProductActivitySkuValue();
            productActivitySkuValue.setPid(productActivity.getId());
            productActivitySkuValue.setVid(attributeValueId);
            productActivitySkuValue.setValue(productAttributeValue.getAttributeValue());
            productActivitySkuValue.setSort(productAttributeValue.getSort());
            productActivitySkuValue.setStatus(SysConfigConstants.STATUS_1);
            productActivitySkuValue.setCreateTime(new Date());
            productActivitySkuValueMapper.insert(productActivitySkuValue);
        }

        //同步 活动商品推荐信息
        ProductMatching productMatching = productMatchingDao.getProductMatching(productActivity.getProductId());
        if (productMatching != null) {
            ProductActivityMatching productActivityMatching = new ProductActivityMatching();
            productActivityMatching.setProductId(productActivity.getId());
            productActivityMatching.setSex(productMatching.getSex());
            productActivityMatching.setComsumerPower(productMatching.getComsumerPower());
            productActivityMatching.setAgeStr(productMatching.getAgeStr());
            productActivityMatching.setProvinceJson(productMatching.getProvinceJson());
            productActivityMatching.setLabelJson(productMatching.getLabelJson());
            productActivityMatching.setCreateTime(new Date());
            productActivityMatchingMapper.insertSelective(productActivityMatching);
        }

        return count;
    }

    @Override
    public List<ActivityColumn> getColumnByType(String type) {
        ActivityColumnExample activityColumnExample = new ActivityColumnExample();
        activityColumnExample.setOrderByClause("sort asc");
        activityColumnExample.createCriteria().andTypeEqualTo(type).andStatusEqualTo(SysConfigConstants.STATUS_1);
        return activityColumnMapper.selectByExample(activityColumnExample);
    }

    @Override
    public CommonPage<ProductSpecial> getProductSpecial(ProductSpecialRequest productSpecialRequest) {
        PageHelper.startPage(productSpecialRequest.getPageNum(), productSpecialRequest.getPageSize());
        List<ProductSpecial> page = productDao.getProductSpecial(productSpecialRequest);
        return CommonPage.restPage(page);
    }

    @Override
    public CommonPage<ProductSpec> getProductSpec(ProductSpecRequest productSpecRequest) {
        PageHelper.startPage(productSpecRequest.getPageNum(), productSpecRequest.getPageSize());
        List<ProductSpec> page = productDao.getProductSpec(productSpecRequest);
        return CommonPage.restPage(page);
    }

    @Override
    public Integer updateProductSpecImg(ProductSpecRequest productSpecRequest) {
        Integer[] specId = productSpecRequest.getSpecId();
        Integer count = 0;
        if (specId.length > 0) {
            for (int i = 0; i < specId.length; i++) {
                count = productDao.updateProductSpecImg(productSpecRequest.getProImg(), specId[i]);
            }
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProductSpec(ProductSpec productSpec) {
        productSpec.setUpdateTime(new Date());
        int count = productSpecMapper.updateByPrimaryKeySelective(productSpec);

        // 重新计算总库存 set 总库存
        Integer stockSum = productSpecDao.queryStockSum(productSpec.getProductId());
        if (stockSum == null) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.PRODUCT_NO_SPECIFICATION));
        }
        Product product = new Product();
        product.setId(productSpec.getProductId());
        product.setStock(stockSum);
        productMapper.updateByPrimaryKeySelective(product);
        return count;
    }

    @Override
    public CommonPage<ProductImg> getProductImgs(ProductImgRequest productImgRequest) {
        PageHelper.startPage(productImgRequest.getPageNum(), productImgRequest.getPageSize());
        List<ProductImg> page = productDao.getProductImgs(productImgRequest);
        return CommonPage.restPage(page);
    }

    @Override
    public ProductMatching getProductMatching(Integer productId) {
        ProductMatchingExample productMatchingExample = new ProductMatchingExample();
        productMatchingExample.createCriteria().andProductIdEqualTo(productId);
        List<ProductMatching> productMatchings = productMatchingMapper.selectByExampleWithBLOBs(productMatchingExample);
        if (!CollectionUtils.isEmpty(productMatchings)) {
            return productMatchings.get(0);
        }
        return null;
    }

    @Override
    public int updateProductMatching(ProductMatching productMatching) {
        // 修改或增加时，需要先判断是否存在改推荐信息记录
        ProductMatchingExample productMatchingExample = new ProductMatchingExample();
        productMatchingExample.createCriteria().andProductIdEqualTo(productMatching.getProductId());
        List<ProductMatching> list = productMatchingMapper.selectByExampleWithBLOBs(productMatchingExample);
        if (!CollectionUtils.isEmpty(list)) {
            ProductMatching pm = list.get(0);
            productMatching.setUpdateTime(new Date());
            return productMatchingDao.updateProductMatchingByProduct(productMatching);
        }

        //将商品管理-推荐信息同步到活动商品-推荐信息中
        ProductActivityMatching productActivityMatching = new ProductActivityMatching();
        productActivityMatching.setProductId(productMatching.getProductId());
        productActivityMatching.setSex(productActivityMatching.getSex());
        productActivityMatching.setComsumerPower(productMatching.getComsumerPower());
        productActivityMatching.setAgeStr(productMatching.getAgeStr());
        productActivityMatching.setProvinceJson(productMatching.getProvinceJson());
        productActivityMatching.setLabelJson(productMatching.getLabelJson());
        productActivityMatching.setCreateTime(new Date());
        productActivityMatchingMapper.insert(productActivityMatching);

        productMatching.setCreateTime(new Date());
        return productMatchingDao.insertProductMatching(productMatching);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStockBatch(Integer stock) {
        // 修改所有商品的规格库存
        productSpecDao.updateSpecStocks(stock);
        // 根据商品id分组 进行库存计总
        List<ProductStockGroupResponse> list = productDao.productStockGroup();
        if (!CollectionUtils.isEmpty(list)) {
            for (ProductStockGroupResponse data : list) {
                productDao.updateStock(data.getProductId(), data.getStockSum());
            }
        }
        return list.size();
    }

    /**
     * 根据商品分类id获取规格List
     *
     * @param productCategoryId
     * @return
     */
    private List<Map<String, Object>> getSpecListByAttributeKeyIds(Integer productCategoryId) {
        List<Map<String, Object>> spec_array = new ArrayList<>();

        ProductAttributeKeyExample productAttributeKeyExample = new ProductAttributeKeyExample();
        productAttributeKeyExample.createCriteria().andCategoryIdEqualTo(productCategoryId);
        List<ProductAttributeKey> productAttributeKeys = productAttributeKeyMapper.selectByExample(productAttributeKeyExample);
        List<Integer> attributeKeyIds = productAttributeKeys.stream().map(ProductAttributeKey::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(attributeKeyIds)) {
            for (Integer attributeKeyId : attributeKeyIds) {
                Map<String, Object> spec_map = new LinkedHashMap<>();
                ProductAttributeKey productAttributeKey = productAttributeKeyMapper.selectByPrimaryKey(attributeKeyId);
                ProductAttributeValueExample productAttributeValueExample = new ProductAttributeValueExample();
                productAttributeValueExample.createCriteria().andAttributeIdEqualTo(productAttributeKey.getId());
                List<ProductAttributeValue> productAttributeValues = productAttributeValueMapper.selectByExample(productAttributeValueExample);
                spec_map.put("spanName", productAttributeKey.getAttributeName());
                if (!CollectionUtils.isEmpty(productAttributeValues)) {
                    List<String> spanValues = new ArrayList<>();
                    for (ProductAttributeValue productAttributeValue : productAttributeValues) {
                        spanValues.add(productAttributeValue.getAttributeValue());
                    }
                    spec_map.put("spanValue", spanValues);
                }
                spec_array.add(spec_map);
            }
        }
        return spec_array;
    }

    private List<String> getDetailByJson(String specJson) {
        JSONArray jsonArray = JSONArray.parseArray(specJson);
        List<String> spanlist = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONArray spanValues = jsonObject.getJSONArray("spanValue");
            for (int j = 0; j < spanValues.size(); j++) {
                String span = jsonObject.getString("spanName") + ":" + spanValues.getString(j);
                if (jsonArray.size() == 1) {
                    spanlist.add(span);
                    continue;
                }
                getSpan(i + 1, span, jsonArray, spanlist);
            }
            break;
        }
        return spanlist;
    }

    private void getSpan(int i, String span, JSONArray jsonArray, List spanlist) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        JSONArray spanValues = jsonObject.getJSONArray("spanValue");
        for (int j = 0; j < spanValues.size(); j++) {
            span = span + "," + jsonObject.getString("spanName") + ":" + spanValues.getString(j);
            if (i == jsonArray.size() - 1) {
                spanlist.add(span);
            } else {
                getSpan(i + 1, span, jsonArray, spanlist);
            }
            span = span.substring(0, span.indexOf("," + jsonObject.getString("spanName") + ":" + spanValues.getString(j)));
        }
    }

    private List<Map<String, Object>> getCheckedSpan(List<Integer> attributeValueIds) {
        Map<String, List<String>> checkedList = new HashMap<>();
        if (!CollectionUtils.isEmpty(attributeValueIds)) {
            for (int i = 0; i < attributeValueIds.size(); i++) {
                Integer attributeValueId = attributeValueIds.get(i);
                ProductAttributeValue data_value = productAttributeValueMapper.selectByPrimaryKey(attributeValueId);
                ProductAttributeKey data_key = productAttributeKeyMapper.selectByPrimaryKey(data_value.getAttributeId());
                String key = data_key.getAttributeName();
                List<String> listValue = checkedList.get(key);
                if (null == listValue || listValue.size() <= 0) {
                    List<String> list = new ArrayList<>();
                    list.add(data_value.getAttributeValue());
                    checkedList.put(key, list);
                } else {
                    listValue.add(data_value.getAttributeValue());
                    checkedList.put(key, listValue);
                }
            }
        }
        List<Map<String, Object>> list = new ArrayList<>();
        checkedList.forEach((key, value) -> {
            Map<String, Object> span = new LinkedHashMap<>();
            span.put("spanName", key);
            span.put("spanValue", value);
            list.add(span);
        });
        return list;
    }

    @Override
    public int updatePriceStock(Integer productId, BigDecimal price, Integer stock, BigDecimal curPrice) {
        return productSpecDao.updatePriceStock(productId, price, stock, curPrice);
    }

    @Override
    public int updateStock(Integer productId, Integer stockSum) {
        return productDao.updateStock(productId, stockSum);
    }

    @Override
    public int isHomeFlag(Integer id, Integer homeFlag) {
        return productDao.isHomeFlag(id, homeFlag);
    }

    @Override
    public CommonPage<ProductStatisticsResponse> queryProductStatistics(ProductStatisticsRequest productStatisticsRequest) {
        PageHelper.startPage(productStatisticsRequest.getPageNum(), productStatisticsRequest.getPageSize());
        List<ProductStatisticsResponse> productStatisticsList = productStatisticsDao.queryProductStatistics(productStatisticsRequest);
        productStatisticsList.stream().map(item -> {
            Integer topCategory = item.getTopCategory();
            ProductCategory productCategory = productCategoryMapper.selectByPrimaryKey(topCategory);
            item.setTopCategoryName(productCategory.getTitle());
            return item;

        }).collect(Collectors.toList());
        return CommonPage.restPage(productStatisticsList);
    }

    @Override
    public List<ProductStatisticsResponse> exportOrdersExcel(ProductStatisticsRequest request) {
        List<ProductStatisticsResponse> productStatisticsList = productStatisticsDao.queryProductStatistics(request);
        productStatisticsList.stream().map(item -> {
            Integer topCategory = item.getTopCategory();
            ProductCategory productCategory = productCategoryMapper.selectByPrimaryKey(topCategory);
            item.setTopCategoryName(productCategory.getTitle());
            return item;

        }).collect(Collectors.toList());
        return productStatisticsList;
    }

    @Override
    public Integer easyShuttle(EasyShuttleRequest easyShuttleRequest) {
        com.ytjj.qmyx.mall.model.Product product = productDao.getProductById(easyShuttleRequest.getId());
        List<ProductActivity> productActivityList = productActivityDao.getProductActivityByProductId(easyShuttleRequest.getId());
        if (!CollectionUtils.isEmpty(productActivityList)) {
            for (ProductActivity activity : productActivityList) {
                if (easyShuttleRequest.getProductName() != null || easyShuttleRequest.getRecommendDoc() != null
                        || easyShuttleRequest.getDescr() != null) {
                    ProductActivity pa = new ProductActivity();
                    pa.setId(activity.getId());
                    pa.setProductName(easyShuttleRequest.getProductName());
                    pa.setRecommendDoc(easyShuttleRequest.getRecommendDoc());
                    pa.setDescr(easyShuttleRequest.getDescr());
                    productActivityDao.updateProductInfo(pa);
                }
            }
        }

        String[] easyType = easyShuttleRequest.getEasyType();
        Integer count = 0;
        if (easyType.length > 0) {
            for (int i = 0; i < easyType.length; i++) {
                List<ProductImg> productImgList = productImgDao.getProductImgInfo(easyShuttleRequest.getId(), easyType[i]);
                for (ProductActivity activity : productActivityList) {
                    productActivityDao.delProductActivityImg(activity.getId(), easyType[i]);
                }
                if (!CollectionUtils.isEmpty(productImgList)) {
                    for (ProductImg pi : productImgList) {
                        if (!CollectionUtils.isEmpty(productActivityList)) {
                            for (ProductActivity activity : productActivityList) {
                                ProductActivityImg pai = new ProductActivityImg();
                                pai.setProductId(activity.getId());
                                pai.setImgUrl(pi.getImgUrl());
                                pai.setSort(pi.getSort());
                                pai.setType(pi.getType());
                                pai.setFileType(pi.getFileType());
                                pai.setCreateTime(new Date());
                                pai.setUpdateTime(new Date());

                                count = productActivityDao.insertProductImg(pai);
                            }
                        }
                    }
                }
            }
        }
        return count;
    }

    @Override
    public CommonPage<StockRemindResponse> getStockInfo(StockRemindRequest stockRemindRequest) {
        PageHelper.startPage(stockRemindRequest.getPageNum(), stockRemindRequest.getPageSize());
        List<StockRemindResponse> pageList = productDao.getStockInfo(stockRemindRequest.getStockNum());
        return CommonPage.restPage(pageList);
    }

    @Override
    public Integer syncSpecInfo() {
        List<ProductModelResponse> pageList = productDao.syncList();
        Integer count = 0;
        if (!CollectionUtils.isEmpty(pageList)) {
            for (ProductModelResponse pmr : pageList) {
                count = productDao.syncSpec(pmr.getId(), pmr.getCurPrice());
            }
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer syncEvaluationProduct(EvaluationProductRequeset evaluationProduct) {
        // 测评商品-->同步至商品管理
        Product product = new Product();
        product.setBankerProductId(evaluationProduct.getBankerProductId());
        product.setEvaluationProductId(evaluationProduct.getId());
        product.setProductNo(evaluationProduct.getProductNo());
        product.setProductName(evaluationProduct.getProductName());
        product.setProductImg(evaluationProduct.getProductImg());
        product.setSceneImg(evaluationProduct.getSceneImg());
        product.setShrinkImg(evaluationProduct.getShrinkImg());
        product.setPrice(evaluationProduct.getPrice());
        product.setDescr(evaluationProduct.getDescr());
        product.setPv(evaluationProduct.getPv());
        product.setStatus((byte) 2);
        product.setSort(evaluationProduct.getSort());
        product.setOriginalPrice(evaluationProduct.getOriginalPrice());
        product.setCurPrice(evaluationProduct.getCurPrice());
        product.setCostPrice(evaluationProduct.getCostPrice());
        product.setStock(evaluationProduct.getStock());
        product.setCommentSum(evaluationProduct.getCommentNum());
        product.setGoodRatio(evaluationProduct.getGoodRatio());
        product.setWarehouse(evaluationProduct.getWarehouse());
        product.setWarehouseName(evaluationProduct.getWarehouseName());
        product.setWarehouseRule(evaluationProduct.getWarehouseRule());
        product.setCategoryId(evaluationProduct.getCategoryId());
        product.setVolume(evaluationProduct.getVolume());
        product.setVolumeStr(evaluationProduct.getVolumeStr());
        product.setAttributeJson(evaluationProduct.getAttributeJson());
        product.setCreateTime(new Date());
        product.setAuditStatus(evaluationProduct.getAuditStatus());
        product.setBankerId(evaluationProduct.getBankerId());
        product.setRate(evaluationProduct.getRate());
        product.setHomeFlag(0);
        product.setRecommendDoc(evaluationProduct.getRecommendDoc());
        product.setRecImgFlag(evaluationProduct.getRecImgFlag());
        product.setDataType(evaluationProduct.getDataType());
        product.setRecDescr(evaluationProduct.getRecDescr());
        product.setIsAdvert(0);
        product.setIsHide(0);
        product.setLongTitle(evaluationProduct.getLongTitle());
        Integer count = productDao.syncEvaluationProduct(product);

        //自增长策略 获取主键id
        Integer productId = product.getId();

        //测评商品img-->普通商品img
        EvaluationProductImgExample evaluationProductImgExample = new EvaluationProductImgExample();
        evaluationProductImgExample.createCriteria().andProductIdEqualTo(evaluationProduct.getId())
                .andStatusEqualTo(1);
        List<EvaluationProductImg> epImgList = evaluationProductImgMapper.selectByExample(evaluationProductImgExample);
        if (!CollectionUtils.isEmpty(epImgList)) {
            for (EvaluationProductImg epi : epImgList) {
                ProductImg pi = new ProductImg();
                pi.setProductId(productId);
                pi.setImgUrl(epi.getImgUrl());
                pi.setSort(epi.getSort());
                pi.setFileType(epi.getFileType());
                pi.setType(epi.getType());
                pi.setCreateTime(new Date());
                productImgMapper.insertSelective(pi);
            }
        }

        //测评商品spec-->普通商品spec
        EvaluationProductSpecExample evaluationProductSpecExample = new EvaluationProductSpecExample();
        evaluationProductSpecExample.createCriteria().andProductIdEqualTo(evaluationProduct.getId())
                .andStatusEqualTo((byte) 1);
        List<EvaluationProductSpec> epSpecList = evaluationProductSpecMapper.selectByExample(evaluationProductSpecExample);
        if (!CollectionUtils.isEmpty(epSpecList)) {
            for (EvaluationProductSpec eps : epSpecList) {
                ProductSpec ps = new ProductSpec();
                ps.setProductId(productId);
                ps.setSkuSpec(eps.getSkuSpec());
                ps.setCurPrice(evaluationProduct.getCurPrice());
                ps.setPrice(evaluationProduct.getPrice());
                if (evaluationProduct.getIsZeroProduct() == 1) {
                    ps.setPrice(new BigDecimal(0));
                }
                ps.setBuySum(evaluationProduct.getVolume());
                ps.setProImg(eps.getProImg());
                ps.setStock(eps.getStock());
                ps.setStatus(eps.getStatus());
                ps.setCreateTime(new Date());
                ps.setBankerProductId(evaluationProduct.getBankerProductId());
                ps.setEvaluationProductId(evaluationProduct.getId());
                productSpecMapper.insertSelective(ps);
            }
        }

        //测评商品sku_key-->普通商品sku_key
        EvaluationProductSkuKeyExample evaluationProductSkuKeyExample = new EvaluationProductSkuKeyExample();
        evaluationProductSkuKeyExample.createCriteria().andPidEqualTo(evaluationProduct.getId());
        List<EvaluationProductSkuKey> epskList = evaluationProductSkuKeyMapper.selectByExample(evaluationProductSkuKeyExample);
        if (!CollectionUtils.isEmpty(epskList)) {
            for (EvaluationProductSkuKey epsk : epskList) {
                ProductSkuKey key = new ProductSkuKey();
                key.setPid(productId);
                key.setKid(epsk.getKid());
                key.setName(epsk.getName());
                key.setSort(epsk.getSort());
                key.setCreateTime(new Date());
                productSkuKeyMapper.insertSelective(key);
            }
        }

        //测评商品sku_value-->普通商品sku_value
        EvaluationProductSkuValueExample evaluationProductSkuValueExample = new EvaluationProductSkuValueExample();
        evaluationProductSkuValueExample.createCriteria().andPidEqualTo(evaluationProduct.getId());
        List<EvaluationProductSkuValue> epsvList = evaluationProductSkuValueMapper.selectByExample(evaluationProductSkuValueExample);
        if (!CollectionUtils.isEmpty(epsvList)) {
            for (EvaluationProductSkuValue epsv : epsvList) {
                ProductSkuValue value = new ProductSkuValue();
                value.setPid(productId);
                value.setVid(epsv.getVid());
                value.setValue(epsv.getValue());
                value.setSort(epsv.getSort());
                value.setStatus(epsv.getStatus());
                value.setCreateTime(new Date());
                productSkuValueMapper.insertSelective(value);
            }
        }

        // 商家消息通知--商品已发布于普通商品
        BankerMessage message = new BankerMessage();
        message.setBankerId(evaluationProduct.getBankerId());
        message.setBankerProductId(evaluationProduct.getBankerProductId());
        message.setProductName(evaluationProduct.getProductName());
        message.setRemarks("您上传的商品,名称：" + evaluationProduct.getProductName() + ",现已同步至普通商品库！");
        message.setStatus(0);
        message.setType(1);
        message.setCreateTime(new Date());
        bankerMessageDao.insertMessage(message);

        return count;
    }

    @Override
    public List<BankerColumn> getColumnList() {
        BankerColumnExample bankerColumnExample = new BankerColumnExample();
        bankerColumnExample.createCriteria()
                .andStatusEqualTo(1);
        List<BankerColumn> bankerColumnList = bankerColumnMapper.selectByExample(bankerColumnExample);
        return Optional.ofNullable(bankerColumnList)
                .orElse(new ArrayList<>());
    }

    @Override
    public List<NewProductResponse> getSmallProductList(NewProductRequest newProductRequest) {
        ProductExample productExample = new ProductExample();
        if (!StringUtils.isEmpty(newProductRequest.getIsGroupBook())){
            productExample.createCriteria()
                    .andProductNameLike("%" + newProductRequest.getProductName() + "%")
                    .andStatusEqualTo((byte) 1)
                    .andIsZeroProductEqualTo(0)
                    .andActivityTypeEqualTo("")
                    .andPlatformDataEqualTo("app");
        }else if (!StringUtils.isEmpty(newProductRequest.getPlatformData())){
            if(PlatformConstant.PROVINCE_PLATFORM.equals(newProductRequest.getPlatformData())){
                List<String> provinceCodes = new ArrayList<>();
                if(!CollectionUtils.isEmpty(provinceCodes)){
                    for (String provinceCode : provinceCodes) {
                        provinceCodes.add(PlatformConstant.PROVINCE_PLATFORM + provinceCode);
                    }
                    productExample.createCriteria()
                            .andProductNameLike("%" + newProductRequest.getProductName() + "%")
                            .andStatusEqualTo((byte) 1)
                            .andIsZeroProductEqualTo(0)
                            .andActivityTypeEqualTo("")
                            .andPlatformDataIn(provinceCodes);
                }else {
                    SalesChannelsManagement saleRequest = new SalesChannelsManagement();
                    saleRequest.setType(3);
                    List<SalesChannelsManagement> allSalesChannels = salesChannelsManagementDao.getAllSalesChannels(saleRequest);
                    for (SalesChannelsManagement province : allSalesChannels) {
                        provinceCodes.add(PlatformConstant.PROVINCE_PLATFORM + province.getCode());
                    }
                    productExample.createCriteria()
                            .andProductNameLike("%" + newProductRequest.getProductName() + "%")
                            .andStatusEqualTo((byte) 1)
                            .andIsZeroProductEqualTo(0)
                            .andActivityTypeEqualTo("")
                            .andPlatformDataIn(provinceCodes);
                }
            }else {
                productExample.createCriteria()
                        .andProductNameLike("%" + newProductRequest.getProductName() + "%")
                        .andStatusEqualTo((byte) 1)
                        .andIsZeroProductEqualTo(0)
                        .andActivityTypeEqualTo("")
                        .andPlatformDataEqualTo(newProductRequest.getPlatformData());
            }
        }else {
            productExample.createCriteria()
                    .andProductNameLike("%" + newProductRequest.getProductName() + "%")
                    .andStatusEqualTo((byte) 1)
                    .andIsZeroProductEqualTo(0)
                    .andActivityTypeEqualTo("");
        }

        List<Product> productList = productMapper.selectByExample(productExample);
        List<NewProductResponse> newProductResponseList = null;
        Map<String,List<SalesChannelsManagement>> saleMap = new HashMap<>();
        if(PlatformConstant.PROVINCE_PLATFORM.equals(newProductRequest.getPlatformData())){
            List<SalesChannelsManagement> salesChannelsManagements = salesChannelsManagementDao.getAllSalesChannels(null);
            if(!CollectionUtils.isEmpty(salesChannelsManagements)){
                saleMap = salesChannelsManagements.stream().collect(Collectors.groupingBy(e -> {
                    String code = "";
                    if(e.getType() == 3){
                        code = PlatformConstant.PROVINCE_PLATFORM+e.getCode();
                    }else {
                        code = e.getCode();
                    }
                    return code;
                }));
            }
        }
        if (productList.size() > 0) {
            Map<String, List<SalesChannelsManagement>> finalSaleMap = saleMap;
            newProductResponseList = productList.stream().map(item -> {
                NewProductResponse response = new NewProductResponse();
                response.setId(item.getId());
                response.setProductName(item.getProductName());
                BigDecimal subsidy = item.getOriginalPrice().subtract(item.getPrice());
                response.setSubsidy(subsidy);
                response.setPlatformData(item.getPlatformData());
                response.setCurPrice(item.getCurPrice());
                List<SalesChannelsManagement> salesChannelsManagements = finalSaleMap.get(item.getPlatformData());
                if(!CollectionUtils.isEmpty(salesChannelsManagements)){
                    response.setPlatformText(salesChannelsManagements.get(0).getName());
                }
                return response;
            }).collect(Collectors.toList());
        }
        return newProductResponseList;
    }

    @Override
    public List<Product> getProductNotInSubject(NewProductRequest newProductRequest) {
        List<Product> productNotInSubject = new ArrayList<>();
        if(org.apache.commons.lang.StringUtils.isNotEmpty(newProductRequest.getProductName())){
            productNotInSubject = productDao.getProductInSubject(newProductRequest.getProductName(),newProductRequest.getPlatformData());
        }
        return productNotInSubject;
    }

    @Override
    public void updateProductActivityType(NewProductRequest newProductRequest) {
        newProductRequest.setProductType(2);
        if (ActivityTypeNameCode.CASH_COUPON.getCode().equals(newProductRequest.getActivityType())) {
            if (newProductRequest.getActivityMax().compareTo(new BigDecimal("50")) == 0) {
                newProductRequest.setColumnId(20);
            } else if (newProductRequest.getActivityMax().compareTo(new BigDecimal("100")) == 0) {
                newProductRequest.setColumnId(21);
            } else {
                newProductRequest.setColumnId(999);
            }
        }
        newProductRequest.setActivityTime(new Date());
        productMapper.updateByPrimaryKeySelective(newProductRequest);
    }

    @Override
    public void updateProductActivityTypeForProvince(NewProductRequest newProductRequest) {
        Integer id = newProductRequest.getId();
        Product product = productMapper.selectByPrimaryKey(id);
        List<Product> products = new ArrayList<>();
        //如果当前是主商品
        if(PlatformConstant.PROVINCE_PLATFORM.equals(product.getPlatformData())){
            SalesChannelsManagement management = new SalesChannelsManagement();
            management.setType(3);
            List<SalesChannelsManagement> allSalesChannels = salesChannelsManagementDao.getAllSalesChannels(management);
            List<String> platforms = allSalesChannels.stream().map(e -> PlatformConstant.PROVINCE_PLATFORM + e.getCode()).collect(Collectors.toList());
            platforms.add(PlatformConstant.PROVINCE_PLATFORM);
            //获取当前主商品的子商品
            products =  productDao.queryBySupplyIdAndPlatformData(Arrays.asList(product.getSupplyProductId()), platforms);
        }else {
            products.add(product);
        }
        for (Product item : products) {
            NewProductRequest newEntity = new NewProductRequest();
            BeanUtils.copyProperties(newProductRequest,newEntity);
            if (ActivityTypeNameCode.CASH_COUPON.getCode().equals(item.getActivityType())) {
                if (item.getActivityMax().compareTo(new BigDecimal("50")) == 0) {
                    item.setColumnId(20);
                } else if (item.getActivityMax().compareTo(new BigDecimal("100")) == 0) {
                    item.setColumnId(21);
                } else {
                    item.setColumnId(999);
                }
            }
            newEntity.setId(item.getId());
            newEntity.setProductType(2);
            newEntity.setActivityTime(new Date());
            productMapper.updateByPrimaryKeySelective(newEntity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProduct(UpdateProductRequest updateProductRequest) {
        productMapper.updateByPrimaryKeySelective(updateProductRequest);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeActivityProduct(Integer id) {
        Product product = new Product();
        product.setId(id);
        product.setActivityMax(new BigDecimal(0));
        product.setActivityMin(new BigDecimal(0));
        product.setExtra("");
        product.setActivityType("");
        product.setProductType(1);
        productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProductSpec(Integer id) {
        productSpecMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<ForumProductResponse> getAllForumProductInfo() {
        List<String> forumNameList = ForumEnumNew.getForumType();
        return forumNameList.stream().map(item -> {
            Integer forumProductNum = productDao.getForumProductNum(item);
            return new ForumProductResponse()
                    .setType(item)
                    .setForumName(ForumEnum.getForumName(item))
                    .setProductNum(forumProductNum);
        }).collect(Collectors.toList());

    }

    public static void main(String[] args) {
        System.out.println(ForumEnum.getForumType());
    }

    @Override
    public List<BankerSiteForumResponse> getBrandList(String bankerName) {
        return bankerDao.getBrandList(bankerName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBrand(Integer bankerId) {
        int bankerNum = productForumDao.getBankerByType(bankerId);
        if (bankerNum > 0) {
            throw new ApiException("您已添加该品牌商，请勿重复添加！");
        }
        ProductForum productForum = new ProductForum();
        productForum.setProductId(bankerId);
        productForum.setType(ProductForumConstant.BRAND_SHOP);
        productForum.setStatus(ProductForumConstant.PRODUCT_FORUM_UP);
        productForum.setCreateTime(new Date());
        productForumMapper.insertSelective(productForum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSort(Integer id, Integer sort) {
        ProductForum productForum = new ProductForum();
        productForum.setId(id);
        productForum.setSort(sort);
        productForumMapper.updateByPrimaryKeySelective(productForum);
    }

    @Override
    public void removeBrand(Integer id) {
        ProductForum productForum = new ProductForum();
        productForum.setId(id);
        productForum.setStatus(ProductForumConstant.PRODUCT_FORUM_OFF);
        productForumMapper.updateByPrimaryKeySelective(productForum);
        // 判断是否存在商品,存在下架
        ProductForumInfoExample productForumInfoExample = new ProductForumInfoExample();
        productForumInfoExample.createCriteria()
                .andForumIdEqualTo(id)
                .andStatusEqualTo(ProductForumConstant.PRODUCT_FORUM_UP);
        List<ProductForumInfo> productForumInfoList = productForumInfoMapper.selectByExample(productForumInfoExample);
        if (productForumInfoList.size() > 0) {
            productForumInfoList.stream().forEach(item -> {
                item.setStatus(ProductForumConstant.PRODUCT_FORUM_OFF);
                productForumInfoMapper.updateByPrimaryKeySelective(item);
            });
        }
    }

    @Override
    public List<BankerSiteForumResponse> getBrandUpList(String bankerName, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<BankerSiteForumResponse> brandUpList = productForumDao.getBrandUpList(bankerName);
        return Optional.ofNullable(brandUpList).orElse(Collections.emptyList());
    }

    @Override
    public CommonPage<ProductLifeResponse> getProductLifeByType(ProductLifeRequest productLifeRequest) {
        PageHelper.startPage(productLifeRequest.getPageNum(), productLifeRequest.getPageSize());

        List<ProductLifeResponse> pageList = new ArrayList<>();

        // 生活馆区：根据活动类型获取新增商品的列表
        if (productLifeRequest.getActivityType() != null) {
            if (productLifeRequest.getActivityType().equals("CASH_SCORE")
                    || productLifeRequest.getActivityType().equals("OLD_FOR_NEW")) {
                // 积分中心、以旧换新
                pageList = productDao.getProductLifeByType(productLifeRequest);
            } else if (productLifeRequest.getActivityType().equals("SECKILL_LIST")) {
                // 秒杀页
                productLifeRequest.setActivityType("SECKILL");
                pageList = productDao.getProductLifeByType(productLifeRequest);
            } else if (productLifeRequest.getActivityType().equals("NEW_RECOMMEND")) {
                // 新品推荐
                productLifeRequest.setActivityType("");
                pageList = productDao.getRecommendProduct(productLifeRequest);
            } else if (productLifeRequest.getActivityType().equals("ZERO_EVALUATION")) {
                // 0元测评
                pageList = productDao.getZeroProduct(productLifeRequest);
            } else if (productLifeRequest.getActivityType().equals("CASH_COUPON")) {
                // 红包专区
                productLifeRequest.setActivityType("CASH_COUPON");
                pageList = productDao.getProductLifeByType(productLifeRequest);
            } else if (productLifeRequest.getActivityType().equals("PICK_UP_LEAK")) {
                // 抄底捡漏
                productLifeRequest.setActivityType("PICK_UP_LEAK");
                pageList = productDao.getLeakProduct(productLifeRequest);
            } else if (productLifeRequest.getActivityType().equals("WALLET_DEDUCTION")) {
                // 钱包抵扣专区
                productLifeRequest.setActivityType("WALLET_DEDUCTION");
                pageList = productDao.getWalletProduct(productLifeRequest);
            } else {
                // 9.9元生活馆区
                pageList = productDao.getAllProductForum(productLifeRequest);
            }
        } else {
            throw new ApiException("活动类型为空，请检查后重试！");
        }

        // 三级分类名称
        if (!CollectionUtils.isEmpty(pageList)) {
            for (ProductLifeResponse pl : pageList) {
                if (pl.getTopCategoryId() != null) {
                    pl.setOneTitle(productCategoryDao.getTitleById(pl.getTopCategoryId()));
                }
                if (pl.getCategoryId() != null) {
                    pl.setTwoTitle(productCategoryDao.getTitleById(pl.getCategoryId()));
                }
                if (pl.getBottomCategoryId() != null) {
                    pl.setThreeTitle(productCategoryDao.getTitleById(pl.getBottomCategoryId()));
                }
            }
        }

        return CommonPage.restPage(pageList);
    }

    @Override
    public Integer addProductLife(ForumAddRequest forumAddRequest) {
        Integer[] productIds = forumAddRequest.getProductIds();

        // 执行增加前，需要判断该商品是否已存在，存在-不允许重复添加商品至生活馆
        if (productIds.length > 0) {
            for (Integer data : productIds) {
                Integer isExist = productForumDao.isExist(data, forumAddRequest.getActivityType());
                if (isExist > 0) {
                    throw new ApiException("已存在商品id为：" + data + " 的数据，请勿重复添加！");
                }
            }
        }

        Integer count = 0;
        int sort = 1;
        for (Integer productId : productIds) {
            ProductForum pf = new ProductForum();
            pf.setProductId(productId);
            pf.setType(forumAddRequest.getActivityType());
            pf.setStatus(1);
            pf.setSort(sort);
            pf.setCreateTime(new Date());
            count = productForumDao.addProductForum(pf);
            sort += 1;
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult returnBackProduct(Integer id, String message) {
        Map<String,String> param = new LinkedMap();
        param.put("bankerProductId", String.valueOf(id));
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/stock/getByProduct", param, supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            throw new ApiException("获取供应链商品信息异常");
        }
        CommonResult commonResult_back = com.alibaba.fastjson.JSONObject.parseObject(resultJson, CommonResult.class);
        if (200 == commonResult_back.getCode()) {
            ProductStockAndSpecResponse response = com.alibaba.fastjson.JSONObject.parseObject(commonResult_back.getData().toString(), ProductStockAndSpecResponse.class);
            if (ProductStatusEnums.UP.getValue() == response.getStatus().byteValue()) {
                throw new ApiException("商品处于上架状态不能打回");
            }
        }

        Map<String, String> map = new HashMap();
        map.put("bankerProductId", String.valueOf(id));
        map.put("message", message);
        String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/rollBack", map, supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
        return commonResult;
    }

    @Override
    public CommonResult removeSupplychianProduct(Integer id, String message) {
        Map<String, String> map = new HashMap();
        map.put("productId", String.valueOf(id));
        map.put("message", message);
        String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/remove", map, supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
        return commonResult;
    }

    public void saveImg(Integer productId, Integer bankerId, List<ProductImgResponse> bannerList, List<ProductImgResponse> infoList) {
        bankerProductDao.deleteOldImg(productId, "banner");
        bankerProductDao.deleteOldImg(productId, "info");
        for (ProductImgResponse productImgRequest : bannerList) {
            if (productImgRequest.getSort() == null) {
                throw new ApiException("商品轮播图-图片排序值不能为空！");
            }
            productImgRequest.setType("banner");
            productImgRequest.setProductId(productId);
            productImgRequest.setBankerId(bankerId);
        }
        for (ProductImgResponse productImgRequest : infoList) {
            if (productImgRequest.getSort() == null) {
                throw new ApiException("商品主图-图片排序值不能为空！");
            }
            productImgRequest.setType("info");
            productImgRequest.setProductId(productId);
            productImgRequest.setBankerId(bankerId);
        }
        bannerList.addAll(infoList);
        bankerProductDao.saveImg(bannerList);
    }

    @Override
    public Integer seckillDate(Integer[] ids, String extra) {
        Integer count = 0;
        for (Integer id : ids) {
            count = productDao.updateSeckillDate(id, extra);
        }
        return count;
    }

    @Override
    public List<ProductCategory> getTopCategoryList() {
        List<ProductCategory> allProductCategorys = channelProductService.getAllProductCategorys();
        List<ProductCategory> collect = allProductCategorys.stream().filter(e -> e.getPid().equals(0)).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<CategoryNow> getTopCategoryListV2() {
        return categoryNowService.getFirstList();
    }

    @Override
    public List<ProductCategory> getChildCategoryList(Integer pid) {
        List<ProductCategory> allProductCategorys = channelProductService.getAllProductCategorys();
        List<ProductCategory> collect = allProductCategorys.stream().filter(e -> e.getPid().equals(pid)).collect(Collectors.toList());
        return collect;
    }

    @Override
    public Integer updateProductParam(ProductParamRequest productParamRequest) {
        return productDao.updateProductParam(productParamRequest);
    }

    @Override
    public String buyerList() {
        Map map = new HashMap<>();
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/buyerList", map, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

    @Override
    public String assistantList() {
        Map map = new HashMap<>();
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/assistantList", map, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

    @Override
    public CommonPage<LifeHomeFlagResponse> getLifeHomeFlagList(LifeHomeFlagRequest lifeHomeFlagRequest) {
        PageHelper.startPage(lifeHomeFlagRequest.getPageNum(), lifeHomeFlagRequest.getPageSize());
        return CommonPage.restPage(productDao.getLifeHomeFlagList(lifeHomeFlagRequest));
    }

    @Override
    public List<HomeFlagResponse> chooseHomeFlag(String platformType, String productName) {
        return productDao.chooseHomeFlag(platformType, productName);
    }

    @Override
    public void homeFlagTrue(Integer id) {
        productDao.updateHomeFlag(id, 1);
    }

    @Override
    public void homeFlagFalse(Integer id) {
        productDao.updateHomeFlag(id, 0);
    }

    /**
     * 根据供应商id修改其下的商品状态
     *
     * @param bankerId
     * @param status
     * @return
     */
    @Override
    public CommonResult updateProductStatusByBankerId(Integer bankerId, Integer status) {
        productDao.updateStatusByBankerId(bankerId, status);
        return CommonResult.success();
    }

    /**
     * 根据品牌id修改旗下的商品状态
     *
     * @param brandId
     * @param status
     * @return
     */
    @Override
    public CommonResult updateProductStatusByBrandId(Integer brandId, Integer status) {
        log.debug("===品牌上下架==={},{}", brandId, status);
        BankerBrand bankerBrand = bankerBrandService.selectById(brandId);
        if (null == bankerBrand) {
            return CommonResult.failed("找不到对应的品牌信息");
        }
        Banker banker = bankerMapper.selectByPrimaryKey(bankerBrand.getBankerId());
        if (null == banker) {
            return CommonResult.failed("找不到品牌对应的供应商信息");
        }
        if (0 == banker.getStatus().intValue() && 1 == status) {
            return CommonResult.failed("供应商已下架，不能继续操作");
        }
        List<Integer> bankerProductList = bankerProductDao.selectIdsByBrandId(brandId);
        if (!CollectionUtils.isEmpty(bankerProductList)) {
            productDao.updateStatusBybankerProductIds(bankerProductList, status);
        }

        return CommonResult.success();
    }

    @Override
    public String newUpdateProductStatusByBrandId(BankerUpdatePutOnRequest request) {
        String json = JSON.toJSONString(request);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/putOnBankerBrand", json, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

    @Override
    public List<Product> getListByBankerProductIds(List<Integer> bankerProductList) {
        List<Product> productList = productDao.queryAllByBankerProductIds(bankerProductList);
        return productList;
    }

    @Override
    public Integer judgeStatus(Integer productId) {
        return productDao.judgeStatus(productId);
    }

    @Override
    public CommonResult updateImgToTable() {
        final Integer[] sum = {0};
        ProductImgExample productImgExample = new ProductImgExample();
        productImgExample.createCriteria().andTypeEqualTo("info").andImgUrlIsNotNull();
        List<ProductImg> productImgs = productImgMapper.selectByExample(productImgExample);
        productImgs.stream().forEach(item ->{
            item.setImgUrl("<img src=\""+item.getImgUrl()+"\">");
        });
        Set<Integer> collect = productImgs.stream().map(ProductImg::getProductId).collect(Collectors.toSet());
        List<Integer> productIdList = new ArrayList<>(collect);
        productIdList.stream().forEach(item ->{
            String infoImg = "";
            List<String> imgUrlList = productImgs.stream().filter(productImg -> productImg.getProductId().equals(item)).map(ProductImg::getImgUrl).collect(Collectors.toList());
            for (String s : imgUrlList) {
                infoImg = infoImg + s;
            }
            String infoImgFinal = "<p><br></p><p>" + infoImg + "</p>";
            Integer count = productMapper.updateInfoImgById(item, infoImgFinal);
            sum[0] = sum[0] + count;
        });
        return CommonResult.success(sum[0]);
    }

    @Override
    public void copyProduct(String platform) {

        List<Product> productList = productDao.findProductNo(platform);
        for (Product product : productList){
            log.info("=========================start======================");
            try {
                Integer h5ProductId = productDao.findProductIdByProductNo(product.getProductNo());
                //已经复制过跳过
                List<ProductImg> copyimgList = productDao.findProductImgByProductId(product.getId());
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(copyimgList)){
                    continue;
                }

                //复制商品图片
                List<ProductImg> imgList = productDao.findProductImgByProductId(h5ProductId);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(imgList)){
                    for (ProductImg img : imgList){
                        img.setProductId(product.getId());
                        img.setCreateTime(new Date());
                        productImgMapper.insertSelective(img);
                    }
                }
                //复制商品skukey
                List<ProductSkuKey> skuKeyList = productDao.findProductSkuKeys(h5ProductId);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(skuKeyList)){
                    for (ProductSkuKey skukey:skuKeyList){
                        ProductSkuKey newSkukey = new ProductSkuKey();
                        newSkukey.setPid(product.getId());
                        newSkukey.setName(skukey.getName());
                        newSkukey.setSort(skukey.getSort());
                        newSkukey.setSupplySkuKeyId(skukey.getSupplySkuKeyId());
                        newSkukey.setCreateTime(new Date());
                        productSkuKeyMapper.insertSelective(newSkukey);

                        //复制商品skuvalue
                        List<ProductSkuValue> productSkuValueList = productDao.findProductSkuValues(skukey.getId());
                        for (ProductSkuValue skuValue:productSkuValueList){
                            skuValue.setPid(product.getId());
                            skuValue.setKid(newSkukey.getId());
                            skuValue.setCreateTime(new Date());
                            productSkuValueMapper.insertSelective(skuValue);
                        }
                    }
                }
                //复制商品skuspec
                List<ProductSpec> productSpecList = productDao.findProductSpecs(h5ProductId);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(productSpecList)){
                    for (ProductSpec spec:productSpecList){
                        spec.setProductId(product.getId());
                        spec.setCreateTime(new Date());
                        productSpecMapper.insertSelective(spec);
                    }
                }
            } catch (Exception e) {
                log.error("copyProduct错误,{}",e);
                FeiShuUtil.sendMsg(String.format("copyProduct错误,{}", e.getMessage()));
            }
            log.info("=========================end======================");
        }
    }

    @Override
    public int importProductReviews(List<ImportProductReviewsRequest> productReviews) {
        Integer result = 0;
        if (!CollectionUtils.isEmpty(productReviews)) {
            for (ImportProductReviewsRequest productReview : productReviews) {
                ProductReviews reviews = new ProductReviews();
                reviews.setNickname(productReview.getNickname());
                reviews.setContent(productReview.getContent());
                reviews.setProductId(Integer.parseInt(productReview.getProductId()));
                reviews.setProductName(productReview.getProductName());
                List<String> productList = new ArrayList<>();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(productReview.getProductImg1())) {
                    productList.add(productReview.getProductImg1());
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(productReview.getProductImg2())) {
                    productList.add(productReview.getProductImg2());
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(productReview.getProductImg3())) {
                    productList.add(productReview.getProductImg3());
                }
                reviews.setProductImg(CollectionUtils.isEmpty(productList) ? "" : productList.stream().collect(Collectors.joining(",")));
                productReviewsMapper.insertRandomTime(reviews);
                result++ ;
            }
        }
        return result;
    }

    @Override
    public List<ProductReviews> getProductReviews(List<Integer> productIds) {
        if (CollectionUtils.isEmpty(productIds)) {
            throw new ApiException("供应链商品id不能为空");
        }
        ProductReviewsExample example = new ProductReviewsExample();
        example.createCriteria().andProductIdIn(productIds);
        return productReviewsMapper.selectByExample(example);
    }

    @Override
    public YxProduct getSupplyProduct(Integer supplyProductId) {
        //查询供应链商品信息
        ProductReceiveRequest productReceiveRequest = new ProductReceiveRequest();
        productReceiveRequest.setProductIds(Lists.newArrayList(supplyProductId));
        String json = JSON.toJSONString(productReceiveRequest);
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getByIds", json, supplyApiConfig.getHeadsMap());
        List<YxProduct> yxProducts = null;
        if (!StringUtils.isEmpty(result)) {
            yxProducts = JSONObject.parseArray(result, YxProduct.class);
        }


        return CollectionUtils.isEmpty(yxProducts) ? null :yxProducts.get(0) ;
    }
}
